c - 为什么看起来数组在 ac union 中被反向索引?
问题描述
在 c 中创建无符号整数和 4 字节数组的联合时,字节的顺序似乎颠倒了。为什么是这样?
对于具有二进制表示 10000000 00000000 00000000 00000000 的整数,我希望 b[0] = 10000000,b[1] = 00000000 等。
#include <stdio.h>
#include <stdlib.h>
typedef union intByteRep{
unsigned int i; // 00000000 00000000 00000000 00000000
unsigned char b[4]; // b[0] b[1] b[2] b[3] - What we would expect
// b[3] b[2] b[1] b[0] - What is happening
} intByteRep;
char *binbin(int n);
int main(int argc, char **argv) {
intByteRep ibr;
ibr.i = 2147483648; // 10000000 00000000 00000000 00000000
for(int i = 0; i < 4; i++){
printf("%s ", binbin(ibr.b[i]));
}
printf("\n"); // prints 00000000 00000000 00000000 10000000
for(int i = 3; i >= 0; i--){
printf("%s ", binbin(ibr.b[i]));
}
printf("\n"); // prints 10000000 00000000 00000000 00000000
return 0;
}
/*function to convert byte value to binary string representation*/
char *binbin(int n)
{
static char bin[9];
int x;
for(x=0; x<8; x++)
{
bin[x] = n & 0x80 ? '1' : '0';
n <<= 1;
}
bin[x] = ' ';
return(bin);
}
解决方案
因为你的系统是小端的。
32位整数0x11223344
存储在内存中0x44 0x33 0x22 0x11
在大端系统上,它将存储为:0x11 0x22 0x33 0x44
顺便说一句,大多数流行的 uP 都是小端序。
推荐阅读
- mps - JetBrains 元编程系统不工作
- paperjs - 克隆和符号有什么区别
- amazon-web-services - 如何仅为 AWS Glue 脚本启用粘合日志记录
- reactjs - Redux Toolkit:无法访问服务器发送的错误消息
- c++ - 通过 lambda 函数转发附加参数
- powershell - 无法在powershell脚本中用逗号替换空格
- azure - 删除服务/入口控制器时如何使 Azure 不删除公共 IP?
- powershell - 类实例事件字段始终为空
- bash - 关于bash中日期命令的完整日期格式
- python-3.x - Boto3 运行 ec2 后只返回一个实例 id