Q: 我如何轉換Big-Endian與Little-Endian的格式?
A:
轉換的動作是可逆的 (Big-Endian <-> Little-Endian),下面這個例子可以用來轉換unsigned data types.
inline void endian_swap(unsigned short& x)
{
x = (x>>8) |
(x<<8);
}
inline void endian_swap(unsigned int& x)
{
x = (x>>24) |
((x<<8) & 0x00FF0000) |
((x>>8) & 0x0000FF00) |
(x<<24);
}
// __int64 for MSVC, "long long" for gcc
inline void endian_swap(unsigned __int64& x)
{
x = (x>>56) |
((x<<40) & 0x00FF000000000000) |
((x<<24) & 0x0000FF0000000000) |
((x<<8) & 0x000000FF00000000) |
((x>>8) & 0x00000000FF000000) |
((x>>24) & 0x0000000000FF0000) |
((x>>40) & 0x000000000000FF00) |
(x<<56);
}
Q: 為何不直接使用ntohl()與htonl()就好了?
A: 這二個function:
- 不一定會改變endian-ness
- 不一定具有可攜性 (portability)
更多的資訊,請看
到底ntohl()與htonl()做了什麼?