c++ - 在 "uint8_t | (uint8_t << 8)"中是否有不同的整数提升处理方式?

标签 c++ c integer

在下面的程序中,似乎 a[1] 移动了 8 位并变为 0,打印值应该为 1。但实际上发生了整数提升,b 的打印值为 257。我正在运行 gcc x86-64 上的版本 4.8.2。

这里的问题是:是否会以不同的方式处理整数提升,以便在不通过更改处理器和编译器(处理器选项仅限于 x86、x86-64 和所有 ARM)来更改代码的情况下打印值不是 257?

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

int main(){
  uint8_t *a;
  a = (uint8_t *)malloc(sizeof(uint8_t)*2);
  uint16_t b;
  a[0] = 1; a[1] = 1;
  b = a[0] | (a[1] << 8);
  printf("b = %d\n", b);
  return 0;
}

最佳答案

will integer promotion be handled in a different way so the print value is not 257?

没有。整数提升总是发生,这意味着 a[0]a[1] 在移位或按位或之前被提升为 int发生。

来自规范:

If an int can represent all values of the original type (as restricted by the width, for a bit-field), the value is converted to an int...

关于c++ - 在 "uint8_t | (uint8_t << 8)"中是否有不同的整数提升处理方式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25903655/

相关文章:

c++ - 部署不起作用且可执行扩展

c++ - 这个函数发生了什么?

c - 从两个输入文件读取字符时如何修复 'Segmentation Fault(core dumped)' 错误?

c - ICU u_fgetfile 与 VS2012 发布版本中的运行时不兼容

loops - Julia,使用 map 多次运行一个函数,

构造函数中的 C++14 constexpr union 条件初始化

C++ static constexpr 成员在类外重新声明

c - 从 inotify_event 中检索完整路径名

c++ - 指针只是一个整数吗?

c++ - 在 C++ 中将 int 转换为字符串的最简单方法