使用左移和按位或将两个无符号字节组合成一个整数值

Combining two unsigned bytes to a single integer value using left-shift and bitwise-or

我正在读取 2 个字节,它们一起构成了一个 unsigned short 值,从 0 到 65536。我想将它们组合成一个值,所以这里是我所做的:

int32_t temp; 
uint8_t buffer[2]; 

.............
temp = (buffer[1] << 8) /* [MSByte]*/| (buffer[0]/* [LSByte]*/);

printf (" %d" ,temp) ;

我仍然在 32767 处溢出。知道为什么吗?

在移位之前将 byte 转换为 int,即:

((int32_t)buffer[1] << 8) | buffer[0] 

P.S。 2个字节可以存储[0, 65535]范围内的无符号整数值;您提到的 65536 的值超出范围。


完整的测试程序 — 在 buffer 中尝试不同的字节值:

#include <stdio.h>
#include <stdint.h>

int main()
{
//uint8_t buffer[2] = {255, 0  }; // prints   255
//uint8_t buffer[2] = {255, 127}; // prints 32767
  uint8_t buffer[2] = {255, 255}; // prints 65535

  int32_t temp = ((int32_t)buffer[1] << 8) | buffer[0];

  printf("%d", temp);
}