无符号长移位 [英] 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;
我希望l2也具有2147483648的值,但它会打印18446744071562067968.我假设第一个字节的位移会导致问题?
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的计算以使其返回正确的值.
Hopefully somebody can explain why this fails and how I modify the calculation of l2 so that it returns the correct value.
谢谢.
推荐答案
存储在char中的0x80值是带符号的数量.当您将此类型转换为更广泛的类型时,该值将被符号扩展以保持与更大的类型相同的值.
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.
将第一行中的 char
的类型更改为 unsigned char
,您将不会看到扩展名.
Change the type of char
in the first line to unsigned char
and you will not get the sign extension happening.
要简化您的情况,请运行以下命令:
To simplify what is happening in your case, run this:
char c = 0x80
unsigned long l = c
cout << l << endl;
您将获得以下输出:
18446744073709551488
它是-128作为64位整数(0x80是-128作为8位整数).
which is -128 as a 64-bit integer (0x80 is -128 as a 8-bit integer).
这篇关于无符号长移位的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!