Last active
March 7, 2023 18:42
-
-
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
This file contains 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
#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