c - 将一个字节移位超过 8 位

标签 c bit-manipulation

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] 被提升intunsigned 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/

相关文章:

c - sqlite3(C语言): no such column

c - C中扫描和打印字符串的段错误

C编程: How could you compare two types without ==

c++ - 获取整数位集中前导 1 位置的最快方法?

c - 将位数减少 1

c++ - 如何在 C++ 中计算二进制位?

C 在新行中一个接一个地写数字

c - 用于从路径中提取文件名的可移植纯 C 函数

c - 扩展名为 "h.in"的文件是什么意思?

c - 〜对整数值有什么作用?此操作的用法