Skip to content

Instantly share code, notes, and snippets.

@esnosy
Last active March 7, 2023 18:42
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 esnosy/ab3035a9d89eaa77d2923b03f890781e to your computer and use it in GitHub Desktop.
Save esnosy/ab3035a9d89eaa77d2923b03f890781e to your computer and use it in GitHub Desktop.
Generic integer byte swap function for C++11, C++23 already has one https://en.cppreference.com/w/cpp/numeric/byteswap
#pragma once
#include <type_traits>
template <typename Integer,
std::enable_if_t<std::is_integral<Integer>::value, bool> = true>
static Integer swap_bytes(Integer value)
{
Integer out;
for (int i = 0; i < sizeof(value); i++)
{
reinterpret_cast<char *>(&out)[sizeof(value) - i - 1] = reinterpret_cast<char *>(&value)[i];
}
return out;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment