Skip to content

Instantly share code, notes, and snippets.

@gomons gomons/endianness.cpp
Last active Apr 3, 2016

Embed
What would you like to do?
Convert endianness of integral types.
// Original: http://stackoverflow.com/a/12867287/1091536
// Usage:
// To convert from given endian to host, use:
// host = endian(source, endian_of_source)
// To convert from host endian to given endian, use:
// output = endian(hostsource, endian_you_want_to_output)
enum class Endian: int {
Big = 1, Little = 0
};
template <typename T>
T endian(T w, Endian endian)
{
// this gets optimized out into if (endian == host_endian) return w;
union { uint64_t quad; uint32_t islittle; } t;
t.quad = 1;
if (t.islittle ^ static_cast<int>(endian)) return w;
T r = 0;
// decent compilers will unroll this (gcc)
// or even convert straight into single bswap (clang)
for (int i = 0; i < sizeof(r); i++) {
r <<= 8;
r |= w & 0xff;
w >>= 8;
}
return r;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.