在here 从字节缓冲区转换回 unsigned long int 时:
unsigned long int anotherLongInt;
anotherLongInt = ( (byteArray[0] << 24)
+ (byteArray[1] << 16)
+ (byteArray[2] << 8)
+ (byteArray[3] ) );
其中 byteArray 声明为 unsigned char byteArray[4];
问题:
我以为 byteArray[1]
只是一个无符号字符(8 位)。当左移 16 位时,不是将所有有意义的位移出并用 0 填充整个字节吗?显然它不是8位。也许它正在移动整个 byteArray 这是一个连续的 4 字节?但我不明白这是怎么回事。
最佳答案
在该算术上下文中,byteArray[0]
被提升 为 int
或 unsigned int
,因此shift 是合法的,甚至可能是明智的(我喜欢在做按位操作时只处理 unsigned
类型)。
6.5.7 Bitwise shift operators
The integer promotions are performed on each of the operands. The type of the result is that of the promoted left operand.
和整数促销:
6.3.1.1
If an int can represent all values of the original type the value is converted to an int; otherwise, it is converted to an unsigned int. These are called the integer promotions.
关于c - 将一个字节移位超过 8 位,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12131568/