-1

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

  • There are more than 2 sorts of _"Endianness"_ so just 2 conversions (one for each direction) cannot be enough: https://en.wikipedia.org/wiki/Endianness – Richard Critten Mar 02 '18 at 23:30

1 Answers1

0

If the endianness is different, then in either direction the task is to reverse the order of the bytes, so yes, the implementation in either direction is the same.

  • Right, and if the host's endianness is the same as the network (big) then this code should not re-order the bytes it should just be a straight copy from `val` to `data[i]`. Is that what would happen here? – Mike Smith Mar 03 '18 at 00:01