例如:
int main(int argc, char* argv[]){
char a[4]={0,0,0,1};
int *ia=(int *)a;
printf("%d",ia[0]);
}
它打印 16777216,因为它是二进制的 00000001 00000000 00000000 00000000。为什么会转?
最佳答案
The Intel x86 and also AMD64 / x86-64 series of processors use the little-endian format. The least significant byte (LSB) value is at the lowest address. The other bytes follow in increasing order of significance. This is akin to right-to-left reading in hexadecimal order.
因此,当您写入具有递增内存地址的字符数组时,您正在逐字节写入,这不受机器字节序的影响,但是当您尝试将整个 4 个字节作为单个整数值读取时,其向后阅读。
请注意,数组中值的顺序不受机器字节序的影响,但仅对单个“多字节值”中的字节进行重新排序。
了解更多信息 Wikipedia
关于c - 当我将字符数组转换为整数数组时,为什么字节序列会翻转?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56789828/