Created
August 29, 2017 01:37
-
-
Save hikilaka/54f4a4b0100ac6bf1b0b1747ffc502ab to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <cstdint> | |
#include <utility> | |
namespace sysd { | |
constexpr bool is_big_endian() { | |
return __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__; | |
} | |
template<class T, std::size_t... N> | |
constexpr T byte_swap_impl(T t, std::index_sequence<N...>) { | |
return ((((t >> (N * 8)) & (T)(unsigned char)(-1)) << ((sizeof(T) - 1 - N) * 8)) | ...); | |
} | |
template<class T, class U = typename std::make_unsigned_t<T>> | |
constexpr U byte_swap(T t) { | |
return byte_swap_impl<U>(t, std::make_index_sequence<sizeof(T)>{}); | |
} | |
constexpr auto to_network(const auto &t) { | |
if constexpr (is_big_endian()) { | |
return t; | |
} | |
return byte_swap(t); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment