gpt4 book ai didi

c - 当我将字符数组转换为整数数组时,为什么字节序列会翻转?

转载 作者:行者123 更新时间:2023-11-30 18:44:44 24 4
gpt4 key购买 nike

例如:

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.

每个值中的字节顺序在小端机器中是相反的,如下图所示: enter image description here

因此,当您写入具有递增内存地址的字符数组时,您正在逐字节写入,这不受机器字节序的影响,但是当您尝试将整个 4 个字节作为单个整数值读取时,其向后阅读。

请注意,数组中值的顺序不受机器字节序的影响,但仅对单个“多字节值”中的字节进行重新排序。

了解更多信息 Wikipedia

关于c - 当我将字符数组转换为整数数组时,为什么字节序列会翻转?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56789828/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com