大小端续
分析
unsigned int value = 0x12345678;
用unsigned char buf[4]表示value;
大端【地址相反】:
栈底
buf[3]:78
buf[2]:56
buf[1]:34
buf[0]:12
栈顶
小端序:
栈底
buf[3]:12
buf[2]:34
buf[1]:56
buf[0]:78
栈顶
地址 | Big-Endian | Little-Endian |
---|---|---|
0x01000000 | 0x12 | 0x78 |
0x01000001 | 0x34 | 0x56 |
0x01000002 | 0x78 | 0x34 |
0x01000003 | 0x78 | 0x12 |
转换代码
#include <iostream>
using namespace std;
template <typename T>
T Convert(T input)
{
return input;
}
template <>
unsigned int Convert(unsigned int input)
{
input = (input & 0xff000000) >> 24 |
(input & 0x000000ff) << 24 |
(input & 0x00ff0000) >> 8 |
(input & 0x0000ff00) << 8;
return input;
}
template <>
unsigned short Convert(unsigned short input)
{
input = (input & 0xff00) >> 8 |
(input & 0x00ff) << 8;
return input;
}
bool IsLittleEndian()
{
union test
{
uint32_t i;
char c;
};
test temp;
temp.i = 0x01020304;
return (temp.c == 4);
}
bool IsBigEndian()
{
uint32_t tempInt = 0x01020304;
unsigned char* tempChar = (unsigned char*)&tempInt;
return (*tempChar == 1);
}
int main(int argc, char* argv[])
{
unsigned int input = 0x12345678;
printf("before %x\n", input);
printf("after %x\n", Convert(input));
unsigned short input2 = 0x1234;
printf("before %x\n", input2);
printf("after %x\n", Convert(input2));
printf("Is little endian %d.\n", int(IsLittleEndian()));
printf("Is big endian %d.\n", int(IsBigEndian()));
return 0;
}
输出结果:
before 12345678
after 78563412
before 1234
after 3412
Is little endian 1.
Is big endian 0.