位元組序決定多位元組資料在記憶體中的儲存順序,網路通訊、檔案格式、跨平台資料交換皆須處理此議題。本文示範利用 C++ union(共用體)特性,編寫可攜式程式碼偵測系統位元組序。
以 32 位元整數 0x00000001 為例:
大端序: 位址遞增 → 00 00 00 01 小端序: 位址遞增 → 01 00 00 00
union 成員共用同一塊記憶體,大小等於最大成員。宣告含 int 與 char 的 union,將 int 設為 1,檢查 char 成員(最低位址)的值:
#include <iostream>
using namespace std;
void checkEndianness() {
union {
int i;
char c;
} tester;
tester.i = 1; // 0x00000001
if (tester.c == 1) {
cout << "系統採用小端序" << endl;
} else if (tester.c == 0) {
cout << "系統採用大端序" << endl;
} else {
cout << "非預期結果" << endl;
}
}
int main() {
checkEndianness();
return 0;
}

實務開發建議使用標準函式進行位元組序轉換,確保跨平台相容:
htonl() / ntohl():32 位元主機/網路序轉換htons() / ntohs():16 位元轉換std::endian 編譯期偵測:std::endian::native == std::endian::littlememcpy 或 reinterpret_cast 搭配 char* 檢查位元組。