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

标签 c type-conversion

例如:

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/

相关文章:

c - 修改内核模块中的控制寄存器

c++ - 为什么 C 编译器不在 for 循环体内给出重新声明错误?

c - posix 互斥锁没有按预期工作

c - 当长度直到运行时才知道时,如何在 C 中声明和初始化这个结构数组?

javascript - D3 : Convert data to number

c# - 你能限制泛型中 Type 的类型吗?

python - C/Python 中的国际数据加密算法(IDEA)

c++用户定义的转换 - 隐式转换

c# - 将 List<List<object>> 转换为 List<List<string>>

c++ - 如何将 AnsiString 转换为 char?