場景:
1. 在讀取硬盤數據和媒體數據時,需要根據讀取的數據進行大小端序的轉換,以正確識別數據。其中一個處理就是首先要判斷cpu支持的大小端序情況才能轉換.
2. Little Endian Order: 低地址存低位(整數的高低位)的數據.
test.cpp
#include#include using namespace std; //1.方法1,通過判斷int的低位是否存儲了數值. int IsLittleEndian1() { int x = 1; if (*(char*) &x == 1) { return 1; } else { return 0; } } //1.方法2,使用union的特性判斷低位的int值 int IsLittleEndian2() { union w { int a; char b; }w1; w1.a = 1; return (w1.b == 1); } int main(int argc, char const *argv[]) { cout << "IsLittleEndian1:.................." << endl; if(IsLittleEndian1()) { cout << "Little Endian Order" << endl; }else { cout << "Big Endian Order" << endl; } cout << "IsLittleEndian2:.................." << endl; if(IsLittleEndian2()) { cout << "Little Endian Order" << endl; }else { cout << "Big Endian Order" << endl; } return 0; }
輸出:
IsLittleEndian1:.................. Little Endian Order IsLittleEndian2:.................. Little Endian Order