如何判断机器是大端字节序还是小端字节序
大小端字节序的定义
- 大端字节序:是指一个整数的高位字节(23~31 bit)存储在内存的低地址处,低位字节(0~7 bit)存储在内存的高地址处。
- 小端字节序:是指整数的高位字节存储在内存的高地址处,而低位字节则存储在内存的低地址处。
如何检测自己的电脑是大端字节序还是小端字节序
- 测试代码如下:
#include <iostream> using namespace std; void byteorder() {// 联合体的特点是其所有成员共享相同的内存空间,其大小为最大成员的大小union{short value;char union_bytes[ sizeof( short ) ];} test;// value 和 union_bytes共享同一份内存空间cout << "the size of value is: " << sizeof(test.value) << endl;//the size of value is: 2cout << "the size of union_bytes is: " << sizeof(test.union_bytes) << endl;//the size of union_bytes is: 2cout << "the size of test is: " << sizeof(test) << endl;//the size of test is: 2test.value = 0x0102;//0x0102--->1 0000 0100// 无论大端字节序还是小端字节序,test.union_bytes[ 0 ]都表示联合体的第一个字节,也就是前八个比特位if ( ( test.union_bytes[ 0 ] == 1 ) && ( test.union_bytes[ 1 ] == 2 ) ){cout << "big endian" << endl;}else if ( ( test.union_bytes[ 0 ] == 2 ) && ( test.union_bytes[ 1 ] == 1 ) ){cout << "little endian" << endl;}else{cout << "unknown..." << endl; } }int main() {byteorder();return 0; }
大家可以运行一下,目前主流机器是小端字节序。
-
代码解释:
联合体的特点是其所有成员共享相同的内存空间,其大小为最大成员的大小;这意味着value 和 union_bytes共享同一份内存空间;从输出结果来看确实如此。
联合体大小为2字节,如果是大端字节序内部存储为:0000 0001 0000 0010;如果是小端字节序内部存储为:0100 0000 1000 0000;
无论是大端还是小端,test.union_bytes[ 0 ]都表示联合体第一个字节,test.union_bytes[ 1 ]表示联合体第二个字节。
最终按照大小端逻辑比较即可。