說明
big endian和little endian表示如何存放多字節(jié)數(shù)據(jù)。前者低位字節(jié)排放在內(nèi)存的高端,后者相反。將unsigned long數(shù)據(jù)強(qiáng)制轉(zhuǎn)換成unsigned char*數(shù)據(jù),則它們在兩種模式下的對應(yīng)關(guān)系如下:
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];
實(shí)驗(yàn)代碼
/**
* @file little_big_endian.cpp
* @brief 測試大小端字節(jié)序
* @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;
}
運(yùn)行及結(jié)果
$ g++ little_big_endian.cpp
$ ./a.out
little: (uc[0] + (uc[1]<<8) + (uc[2]<<16) + (uc[3]<<24)) == ul is true
常見問題
字節(jié)序的問題容易出現(xiàn)在不同電腦交互數(shù)據(jù)的時(shí)候,因此當(dāng)數(shù)據(jù)輸出時(shí)——保存成文件或在網(wǎng)絡(luò)上傳輸——就應(yīng)該考慮字節(jié)序。