签名整数的字节序转换 [英] Endian conversion of signed ints
问题描述
我正在通过UDP接收大字节序数据,并将其转换为小字节序。消息人士说,整数是带符号的,但是当我交换带符号的整数(特别是16位)的字节时,我得到的值不切实际。当我将它们交换为无符号整数时,我得到了期望的结果。我认为源文档可能不正确,并且实际上正在发送未签名的16位整数。但是那为什么重要呢?这些值都应该是正数,并且在16位INT_MAX下很好,所以溢出应该不是问题。我唯一能想到的是(1)文档错误并且(2)执行签名的字节序交换时,我没有正确处理符号位。
I am receiving big endian data over UDP and converting it to little endian. The source says the integers are signed but when I swap the bytes of the signed ints (specifically 16-bit) I get unrealistic values. When I swap them as unsigned ints I get what I expect. I suppose the source documentation could be incorrect and is actually sending unsigned 16-bit ints. But why would that matter? The values are all supposed to be positive and well under 16-bit INT_MAX so overflow should not be an issue. The only thing I can think of is that (1) the documentation is wrong AND (2) I am not handling the sign bit properly when I perform a signed endian swap.
我确实有两个问题:
1)当溢出不是问题时,无论我读入带符号或无符号整数都无关紧要。
1) When overflow is not an issue, does it matter whether I read into signed or unsigned ints.
2)有符号和无符号值之间的字节序交换是否不同(即符号位需要以不同方式处理)?
2) Is endian swapping different between signed and unsigned values (i.e. does the sign bit need to be handled differently)?
我认为字节序有符号和无符号值的转换看起来都相同,例如对于16位 value = value& 0xff00>> 8 |值& 0x00ff<< 8
。
I thought endian conversion looked the same for both signed and unsigned values, e.g. for 16-bit value = value&0xff00 >> 8 | value&0x00ff << 8
.
谢谢
推荐答案
您在交换功能中遇到符号扩展的问题。而不是这样做:
You are running into problems with sign extensions in your swap function. Instead of doing this:
value & 0xff00 >> 8 | value & 0x00ff << 8
执行以下操作:
((value >> 8) & 0x00ff) | ((value & 0x00ff) << 8)
问题是如果 value
是一个16位带符号的值,然后 0xabcd>> 8
是 0xffab
。如果在有符号右移中以1开始,最高有效位保持为1。
The issue is that if value
is a 16-bit signed value, then 0xabcd >> 8
is 0xffab
. The most significant bit stays 1 if it starts out as 1 in a signed right shift.
最后,不要自己编写此函数,而应使用 ntohs()
。
Finally, instead of writing this function yourself you should use ntohs()
.
这篇关于签名整数的字节序转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!