简体   繁体   English

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

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

I'm reading 2 bytes which together build up an unsigned short value, from 0 to 65536. I want to combine them to a single value, so here what I've done: 我正在读取2个字节,它们共同构建一个unsigned short值,从0到65536.我想将它们组合成一个值,所以我在这里做了:

int32_t temp; 
uint8_t buffer[2]; 

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

printf (" %d" ,temp) ;

I still get an overflow at 32767. Any idea why? 我仍然在32767溢出。任何想法为什么?

Cast byte to int before shifting, ie: 在转移之前将字节转换为int,即:

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

PS 2 bytes can store an unsigned integer value in range of [0, 65535]; PS 2字节可以存储[0,65535]范围内的无符号整数值; the value of 65536 you've mentioned is out of range. 您提到的65536的值超出范围。


Complete test program — try different byte values in buffer : 完整的测试程序 - 在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);
}

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

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