| 0x87654321 放記憶體的情形 | |||||||||
| big endian | little endian | ||||||||
|---|---|---|---|---|---|---|---|---|---|
| 資料 | 0x87 | 0x65 | 0x43 | 0x21 | 0x21 | 0x43 | 0x65 | 0x87 | |
| 位址 | 0 | 1 | 2 | 3 | 0 | 1 | 2 | 3 | |
x86 處理器就是典型使用 little endian 的處理器,而網路封包欄位通常是高位元組先送收,在記憶體會高位元組先放,所以是 big endian。如果資料的 endian 跟處理器不同,要運算時需要作 endian 轉換。
主機 (host,也就處理器架構) 的 byte order 跟不同 endian 的轉換函數:
- uint16_t htobe16(uint16_t)
- uint16_t htole16(uint16_t)
- uint16_t be16toh(uint16_t)
- uint16_t le16toh(uint16_t)
網路封包的欄位可以用上述 big endian 轉換的函數,但通常用 ntohs()、htons()、ntohl()、htonl() 函數。
問題:需要 preprocessor macro 嗎?有標準的 macro?
沒有留言:
張貼留言