1 字节序
大端、小端没有标准可循,都有系统使用;把给定系统所用是字节称为主机字节序;
系统能够在复位或运行时,在大端和小端之间进行切换;
【网络协议】:发送协议栈和接收协议栈中必须就这些多字节阶段各个字节的传送顺序达成一致;
- 网际协议使用大端字节序来传送这些字节;
为计算机内存中数字数据的字节顺序或序列,也可用于描述比特在通信信道上传输的顺序;
- big-endian(大端):将字的最高有效字节存储在最小的内存地址,而最低有效字节存储在最大的内存地址;
- little-endian(小端):将最低有效字节存储在最小地址;
big-endian是网络协议中最主要的顺序;
little-endian是处理器架构及其相关内存的主要顺序;
字节序存储的重要性
2 大小端验证方法
方式一:
/** 查看当前系统使用大端还是小端 */
8 #include <iostream>
9
10 using namespace std;
11
12
13 void test() {
14 union {
15 short s;
16 char c[sizeof(short)];
17 }un;
18 /*
19 * short为两字节
20 * 0x0102:
21 * 若为大端:0x0102
22 * 若为小端:0x0201
23 * */
24 un.s = 0x0102; // 查看它的两个连续字节c[0]和c[1]的地址,来确定字节序
25 if(sizeof(short) == 2) {
26 if(un.c[0] == 1 && un.c[1] == 2)
27 cout << "big-endian" << endl;
28 else if(un.c[0] == 2 && un.c[1] == 1)
29 cout << "little-endian" << endl;
30 else
31 cout << "unknown" << endl;
32 }else {
33 cout << "sizeof(short) = " << sizeof(short) << endl;
34 }
35 exit(0);
36 }
37
38 int main(int argc, char* argv[])
39 {
40 test();
41
42 return 0;
43 }
方式二
采用系统提供的宏定义来判断
- BYTE_ORDER:为机器的字节序;
- BIG_ENDIAN:大端;
- LITTEL_ENDIAN:小端;
3 大端小端转换
template<class T>
typename std::enable_if<sizeof(T) == sizeof(uint64_t), T>::type
byteswap(T val) {
return (T)bswap_64((uint64_t)val);
}
template<class T>
typename std::enable_if<sizeof(T) == sizeof(uint32_t), T>::type
byteswap(T val) {
return (T)bswap_32((uint32_t)val);
}
template<class T>
typename std::enable_if<sizeof(T) == sizeof(uint16_t), T>::type
byteswap(T val) {
return (T)bswap_16((uint16_t)val);
}
void test() {
uint64_t x = 0x12345678;
printf("%X\n", x);
printf("%lx\n", byteswap(x));
}