判断字节序(以2字节的short为例)
#include <stdio.h>
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) )
{
printf("big endian");
}//低位在低字节
else if ( (test.union_bytes[0] == 2 && (test.union_bytes[1] == 1)) )
{
printf("little endian") ;
}
}
字节序转换(以2字节的short为例)
short swapByteOrder(short x){
short y;
char* a = (char*)(&y);
a[0] = (0x00ff & x) << 8;
a[1] = (0xff00 & x) >> 8;
return y;
}