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