简体   繁体   English

无符号长位移位

[英]Unsigned long and bit shifting

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? 我希望l2也有2147483648的值,但它打印18446744071562067968。我假设第一个字节的位移会导致问题?

Hopefully somebody can explain why this fails and how I modify the calculation of l2 so that it returns the correct value. 希望有人可以解释为什么这会失败以及我如何修改l2的计算以便它返回正确的值。

Thanks in advance. 提前致谢。

Your value of 0x80 stored in a char is a signed quantity. 存储在char中的0x80值是带符号的数量。 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 to unsigned char and you will not get the sign extension happening. 将第一行中的char类型更改为unsigned char并且不会发生符号扩展。

To simplify what is happening in your case, run this: 要简化您的案例中发生的事情,请运行以下命令:

char c = 0x80
unsigned long l = c
cout << l << endl;

You get this output: 你得到这个输出:

18446744073709551488

which is -128 as a 64-bit integer (0x80 is -128 as a 8-bit integer). -128为64位整数(0x80为-128为8位整数)。

Same result here (Linux/x86-64, GCC 4.4.5). 这里的结果相同(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 . 行为取决于unsigned long的大小, 至少为 32位,但可能更大

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). 如果你想要32位,请使用uint32_t (来自头文件<stdint.h> ;不是在C ++ 03中,而是在即将推出的标准中并得到广泛支持)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM