在計算機科學領域中,字節序是指存放多字節數據的字節(byte)的順序,典型的情況是整數在內存中的存放方式和網絡傳輸的傳輸順序。不同的處理器所採用的字節序可能是不同的,例如: x86,6502, Z80, VAX,和 PDP-11都是採用小端字節序,而 Motorola 6800 、 68k, IBM POWER, 和 System/360則採用大端字節序。另外,網絡協議通常也會規定其所採用的字節序,還有像java這樣的語言,也是規定了字節序的(tcp/ip和java都是採用大端字節序)。
通常,系統中會提供ntohs、htons、ntohl、htonl這4個函數,已實現16位和32位本地字節序和網絡字節序的轉換。但是,目前好像還沒有提供64位數據字節序的轉換函數。所以,在這裏自己動手寫一個。
首先,我們要判斷本地系統所採用的字節序:
- #define BigEndian 1
- #define LittleEndian 0
- static bool BigEndianTest()
- {
- /*定義一個2個字節長度的數據,並賦值爲1,則n的16進製表示爲0x0001
- 如果系統以“大端”存放數據,也即是以MSB方式存放,那麼低字節存放的必定是0x00,高字節存放的必定是0x01
- 如果系統以“小端”存放數據,也即是以LSB方式存放,那麼低字節存放的必定是0x01,高字節存放的必定是0x00
- 所謂MSB,就是將最重要的位存入低位,而LSB則是將最不重要的位存入低位
- 我們可以通過檢測低位的數值就可以知道系統的字節序
- */
- const __int16 n = 1;
- if(*(char *)&n)
- {
- return LittleEndian;
- }
- return BigEndian;
- }
當然這裏可以再優化一下,寫成宏定義。
然後,定義16、32、64位的調位函數。這裏就是字節“搬家”而已。
- #define Swap16(s) ((((s) & 0xff) << 8) | (((s) >> 8) & 0xff))
- #define Swap32(l) (((l) >> 24) | /
- (((l) & 0x00ff0000) >> 8) | /
- (((l) & 0x0000ff00) << 8) | /
- ((l) << 24))
- #define Swap64(ll) (((ll) >> 56) |/
- (((ll) & 0x00ff000000000000) >> 40) |/
- (((ll) & 0x0000ff0000000000) >> 24) |/
- (((ll) & 0x000000ff00000000) >> 8) |/
- (((ll) & 0x00000000ff000000) << 8) |/
- (((ll) & 0x0000000000ff0000) << 24) |/
- (((ll) & 0x000000000000ff00) << 40) |/
- (((ll) << 56)))
最後,
- #define BigEndian_16(s) BigEndianTest() ? s : Swap16(s)
- #define LittleEndian_16(s) BigEndianTest() ? Swap16(s) : s
- #define BigEndian_32(l) BigEndianTest() ? l : Swap32(l)
- #define LittleEndian_32(l) BigEndianTest() ? Swap32(l) : l
- #define BigEndian_64(ll) BigEndianTest() ? ll : Swap64(ll)
- #define LittleEndian_64(ll) BigEndianTest() ? Swap64(ll) : ll
現在,我們來測試一下:
- int main()
- {
- unsigned __int16 i16 = 0xabcd;
- unsigned __int32 i32 = 0x0a0b0c0d;
- unsigned __int64 i64 = 0x0102030405060708;
- printf("System is %s/n",BigEndianTest() ? "BigEndian" : "LittleEndian" );
- printf("__int16 i16 = 0x%x, BigEndian:0x%x htons:0x%x, LittleEndian:0x%x ntohs:0x%x/n",
- i16,BigEndian_16(i16),htons(i16),LittleEndian_16(i16),ntohs(BigEndian_16(i16)));
- printf("__int32 i32 = 0x%x, BigEndian:0x%x htons:0x%x, LittleEndian:0x%x ntohs:0x%x/n",
- i32,BigEndian_32(i32),htonl(i32),LittleEndian_32(i32),ntohl(BigEndian_32(i32)));
- printf("__int64 i64 = 0x%llx, BigEndian:0x%llx, LittleEndian:0x%llx/n",i64,
- BigEndian_64(i64),LittleEndian_64(i64));
- getchar();
- return 0;
- }
運行結果如下:
- System is LittleEndian
- __int16 i16 = 0xabcd, BigEndian:0xcdab htons:0xcdab, LittleEndian:0xabcd ntohs:0
- xabcd
- __int32 i32 = 0xa0b0c0d, BigEndian:0xd0c0b0a htons:0xd0c0b0a, LittleEndian:0xa0b
- 0c0d ntohs:0xa0b0c0d
- __int64 i64 = 0x102030405060708, BigEndian:0x807060504030201, LittleEndian:0x102
- 030405060708