所谓的小端法:最低有效字节在最前面的方式。
所谓的大端法:最高有效字节在最前面的方式。
假设变量x 类型为int ,位于地址Oxl00 处,它的十六进制值为0x01234567 。地址范围为0xl00 - 0xl03 的字节,其排列顺序依赖于机器的类型。
下面,给出程序判断机器是大端法还是小端法(现代PC 大多数采用小端法)。
#include "stdafx.h"
#include<iostream>
using namespace std;
void byteorder()
{
union
{
short value;
char union_bytes[sizeof(short)];
} test;
test.value=0x0102;
if((test.union_bytes[0]==1)&&(test.union_bytes[1]==2))
{
cout<<"big"<<endl;
}
else if((test.union_bytes[0]==2)&&(test.union_bytes[1]==1))
{
cout<<"small"<<endl;
}
else
{
cout<<"unknow"<<endl;
}
}
int _tmain(int argc, _TCHAR* argv[])
{
byteorder();
system("pause");
return 0;
}
说明:这里之所以使用union 两个东西共同使用相同的空间,所以没有空间浪费,而且方便操作。
测试结果: