无符号长整型和位移位
我有位移位和无符号长整型的问题。这是我的测试代码:
char header[4];
header[0] = 0x80;
header[1] = 0x00;
header[2] = 0x00;
header[3] = 0x00;
unsigned long l1 = 0x80000000UL;
unsigned long l2 = ((unsigned long) header[0] << 24) + ((unsigned long) header[1] << 16) + ((unsigned long) header[2] << 8) + (unsigned long) header[3];
cout << l1 << endl;
cout << l2 << endl;
我希望 l2 也有一个值 2147483648,但它打印的是 18446744071562067968。我认为第一个字节的位移会导致问题?
希望有人可以解释为什么会失败以及我如何修改 l2 的计算以使其返回正确的值。
提前致谢。
I have a problem with bit shifting and unsigned longs. Here's my test code:
char header[4];
header[0] = 0x80;
header[1] = 0x00;
header[2] = 0x00;
header[3] = 0x00;
unsigned long l1 = 0x80000000UL;
unsigned long l2 = ((unsigned long) header[0] << 24) + ((unsigned long) header[1] << 16) + ((unsigned long) header[2] << 8) + (unsigned long) header[3];
cout << l1 << endl;
cout << l2 << endl;
I would expect l2 to also have a value of 2147483648 but instead it prints 18446744071562067968. I assume the bit shifting of the first byte causes problems?
Hopefully somebody can explain why this fails and how I modify the calculation of l2 so that it returns the correct value.
Thanks in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
存储在 char 中的 0x80 值是一个有符号的数量。当您将其转换为更宽的类型时,该值将被符号扩展以保持与更大类型相同的值。
将第一行中的
char
类型更改为unsigned char
,您将不会发生符号扩展。为了简化您的情况,请运行以下命令:
您将得到以下输出:
64 位整数为 -128(8 位整数为 0x80 为 -128)。
Your value of 0x80 stored in a char is a signed quantity. When you cast this into a wider type, the value is being signed extended to keep the same value as a larger type.
Change the type of
char
in the first line tounsigned char
and you will not get the sign extension happening.To simplify what is happening in your case, run this:
You get this output:
which is -128 as a 64-bit integer (0x80 is -128 as a 8-bit integer).
这里的结果相同(Linux/x86-64,GCC 4.4.5)。该行为取决于
unsigned long
的大小,至少 32 位,但可能更大。如果您想要正好 32 位,请使用
uint32_t
(来自标头
;不是在 C++03 中,而是在即将推出的标准中并得到广泛支持) )。Same result here (Linux/x86-64, GCC 4.4.5). The behavior depends on the size of
unsigned long
, which is at least 32 bits, but may be larger.If you want exactly 32 bits, use a
uint32_t
instead (from the header<stdint.h>
; not in C++03 but in the upcoming standard and widely supported).