說明
big endian和little endian表示如何存放多字節數據。前者低位字節排放在內存的高端,后者相反。將unsigned long數據強制轉換成unsigned char*數據,則它們在兩種模式下的對應關系如下:
big endian:
ul = (uc[0]<< 24) + (uc[1]<<16) + (uc[2]<<8) + uc[3];
little endian:
ul = (uc[3]<<24) + (uc[2]<<16) + (uc[1]<<8) + uc[0];
實驗代碼
/**
* @file little_big_endian.cpp
* @brief 測試大小端字節序
* @copyright public domain
*/
#include <iostream>
static bool is_little_endian() {
union {
long l;
char cs[4];
} t;
t.l = 1;
return t.cs[0] == 1;
}
int main() {
unsigned long ul = 0x12345678;
unsigned char* uc = (unsigned char*)&ul;
if (is_little_endian()) {
bool r = (uc[0] + (uc[1]<<8) + (uc[2]<<16) + (uc[3]<<24)) == ul;
std::cout << "little: (uc[0] + (uc[1]<<8) + (uc[2]<<16) + (uc[3]<<24)) == ul is " << (r ? "true" : "false") << std::endl;
} else {
bool r = (uc[3] + (uc[2]<<8) + (uc[1]<<16) + (uc[0]<<24)) == ul;
std::cout << "little: (uc[3] + (uc[2]<<8) + (uc[1]<<16) + (uc[0]<<24)) == ul is " << (r ? "true" : "false") << std::endl;
}
return 0;
}
運行及結果
$ g++ little_big_endian.cpp
$ ./a.out
little: (uc[0] + (uc[1]<<8) + (uc[2]<<16) + (uc[3]<<24)) == ul is true
常見問題
字節序的問題容易出現在不同電腦交互數據的時候,因此當數據輸出時——保存成文件或在網絡上傳輸——就應該考慮字節序。