字节序,即字节在电脑中存放时的序列与输入(输出)时的序列是先到的在前还是后到的在前。
-- 转自:字节序_百度百科 (baidu.com)
在几乎所有的平台上,多字节对象都被存储为连续的字节序列。例如在 C 语言中,一个类型为int
的变量x
地址为0x100
,那么其指针&x
的值为0x100
。且x
的四个字节将被存储在内存的0x100, 0x101, 0x102, 0x103
位置。
字节的排列方式有两个通用规则:
- 大端序(Big-Endian)将数据的低位字节存放在内存的高位地址,高位字节存放在低位地址。这种排列方式与数据用字节表示时的书写顺序一致,符合人类的阅读习惯。
- 小端序(Little-Endian),将一个多位数的低位放在较小的地址处,高位放在较大的地址处,则称小端序。小端序与人类的阅读习惯相反,但更符合计算机读取内存的方式,因为CPU读取内存中的数据时,是从低地址向高地址方向进行读取的。
举例:
数字0x12345678
小端模式中的存储方式为:
大端模式中的存储方式为:
那么问题来了,怎么判断机器是大端存储还是小端存储呢
(1)使用强制类型转换
/*************************************************************************
> File Name: test.c
> Author: Winter
> Created Time: 2022年07月13日 星期三 19时41分12秒
************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <pthread.h>
int main(int argc, char* argv[])
{
int val = 1;
char* p = (char*)&val;
if (*p == 1) {
printf("小端存储......\n");
} else {
printf("大端存储......\n");
}
return 0;
}
结果
(2)使用联合体
/*************************************************************************
> File Name: test.c
> Author: Winter
> Created Time: 2022年07月13日 星期三 19时41分12秒
************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <pthread.h>
int main(int argc, char* argv[])
{
union {
short value; // 2字节
char bytes[sizeof(short)]; // char[2] 2字节
} test;
test.value = 0x0102;
if ((test.bytes[0] == 1) && (test.bytes[1] == 2)) {
printf("大端存储......\n");
} else if ((test.bytes[0] == 2) && (test.bytes[1] == 1)) {
printf("小端存储......\n");
} else {
printf("未知......\n");
}
return 0;
}
结果