大端字节序与小端字节序
在计算机中,多字节对象被存储在连续的字节序列中,这就引出了存储字节顺序的问题。分为两种模式:1.高位字节在前,也就是大端字节序(Big Endian),或者2.低位字节在前,也就是小端字节序(Little Endian)。
例如对于int n = 0x01020304;
,假设int
大小为4字节,并且该int
对象的地址为0x100
,那么在大端机器和小端机器上内存布局如下图:
测试自己的机器
测试系统是大端字节序还是小端字节序,可以利用C++中union的特性,这里还有个小细节那就是在C++中struct,union,enum类型在使用的时候不必带这几个关键字(在C中是需要的):
#include <iostream>
#include <cstdint>
union Foo {
int16_t whole;
int8_t parts[2];
};
int main(int argc, const char* argv[]) {
Foo foo;
foo.whole = 0x0102;
if (0x01 == foo.parts[0]) {
std::cout << "Big Endian Machine" << std::endl;
} else {
std::cout << "Little Endian Machine" << std::endl;
}
return 0;
}
网络字节序
在TCP/IP中规定网络字节序就是大端字节序。