I've written this code to convert between host and network endianness and found the implementations for both directions is the same. Is that right?
template<typename T>
T be_to_host(T val)
{
T outval = 0;
std::size_t len = sizeof(T);
char *data = reinterpret_cast<char*>(&outval);
// network endian (big) to host endian
for (int i = 0; i < len; i++)
data[i] = (val >> ((len - i - 1) * 8)) & 0xFF;
return outval;
}
template<typename T>
T host_to_be(T val)
{
// works both ways on any platform
return be_to_host<T>(val);
}
I've convinced myself this code is OK but I've always seen different implementations for each direction so I can't shake that feeling that I'm missing something. The fact the 'val' is interpreted as host endianness makes this code bi-direction, right?
Thanks
如果字节序不同,那么在任一方向上的任务是颠倒字节的顺序,所以是的,在任一方向上的实现是相同的。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.