【问题标题】:Combining two unsigned bytes to a single integer value using left-shift and bitwise-or使用左移和按位或将两个无符号字节组合成一个整数值
【发布时间】:2015-04-23 10:48:26
【问题描述】:

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

int32_t temp; 
uint8_t buffer[2]; 

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

printf (" %d" ,temp) ;

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

【问题讨论】:

  • Buffer 是如何声明的?
  • 不清楚你在问什么,也不清楚你想做什么。
  • @iharob 我已经添加了缓冲区的声明

标签: c integer bit-manipulation


【解决方案1】:

在移位前将字节转换为int,即:

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

附: 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);
}

【讨论】:

  • 谢谢你的回答,但我还是得到了溢出
  • @Engine 在我看来就像printf 中的%d 导致了问题,因为%d 是为int 而你的int 似乎是int16_t。试试 C99 格式 printf(PRIi32, temp)en.cppreference.com/w/c/types/integer
  • 感谢大家的帮助,现在可以正常使用了
猜你喜欢
  • 2022-01-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-11-14
  • 1970-01-01
  • 2015-02-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多