大端模式:低地址存储高字节,高地址存储低字节;
小端模式:低地址存储低字节,高地址存储高字节。
如:0x1234,注意计算机是以字节为基本存储单位的。
大端: 0x12 0x34
小端:0x34 0x12
所以判断大小端的方法:
int main()
{
unsigned short a = 0x1234;
unsigned char* ch = (unsigned char*)&a; //ch存储的是低地址内容。
if (*ch == 0x12) cout << "big";
else if (*ch == 0x34) cout << "little";
return 0;
}
转换
//byte转int
int bytes4ToInt(char* bytes)
{
int addr = bytes[0] & 0xFF;
addr |= (bytes[1] << 8 & 0xFF00);
addr |= ((bytes[2] << 16) & 0xFF0000);
addr |= ((bytes[3] << 24) & 0xFF000000);
return addr;
}
大端模式
//byte转int
int bytes4ToInt(char* bytes)
{
int addr = bytes[3] & 0xFF;
addr |= (bytes[2] << 8 & 0xFF00);
addr |= ((bytes[1] << 16) & 0xFF0000);
addr |= ((bytes[0] << 24) & 0xFF000000);
return addr;
}