场景:
1. 在读取硬盘数据和媒体数据时,需要根据读取的数据进行大小端序的转换,以正确识别数据。其中一个处理就是首先要判断cpu支持的大小端序情况才能转换.
2. Little Endian Order: 低地址存低位(整数的高低位)的数据.
test.cpp
#include <stdio.h> #include <iostream> 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
时间: 2024-10-03 06:49:23