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