Skip to content

Instantly share code, notes, and snippets.

@gomons
Last active April 3, 2016 20:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gomons/9d3fb3d44c8f6b95b908a53812005928 to your computer and use it in GitHub Desktop.
Save gomons/9d3fb3d44c8f6b95b908a53812005928 to your computer and use it in GitHub Desktop.
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