Skip to content

Instantly share code, notes, and snippets.

@hikilaka
Created August 29, 2017 01:37
Show Gist options
  • Save hikilaka/54f4a4b0100ac6bf1b0b1747ffc502ab to your computer and use it in GitHub Desktop.
Save hikilaka/54f4a4b0100ac6bf1b0b1747ffc502ab to your computer and use it in GitHub Desktop.
#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