//小端转大端 int little2big(int le) { return (le & 0xff) << 24 | (le & 0xff00) << 8 | (le & 0xff0000) >> 8 | (le >> 24) & 0xff; } //大端转小端 int big2little(int be) { return ((be >> 24) &0xff ) | ((be >> 8) & 0xFF00) | ((be << 8) & 0xFF0000) | ((be << 24)); }
short大小端转换
小端转大端 short little2bigs(short num) { short swapped = (num >> 8) | (num << 8); return swapped; } 大端转小端 short big2littles(short be) { short swapped = (be << 8) | (be >> 8); return swapped; }
32大端转小端原理
swapped = ((num>>24)&0xff) | // move byte 3 to byte 0 ((num<<8)&0xff0000) | // move byte 1 to byte 2 ((num>>8)&0xff00) | // move byte 2 to byte 1 ((num<<24)&0xff000000); // byte 0 to byte 3
内置函数(传入大端转小端,小端转大端,以下同理)
16位无符号,大小端转换
unsigned short _byteswap_ushort(unsigned short value);
32位无符号,大小端转换
unsigned long _byteswap_ulong(unsigned long value);
64位无符号,大小端转换
unsigned __int64 _byteswap_uint64(unsigned __int64 value);
参考来源:
convert big endian to little endian in C [without using provided func]
Converting Little Endian to Big Endian
How do I convert between big-endian and little-endian values in C++?