Skip to content

Instantly share code, notes, and snippets.

@visuve
Created December 7, 2021 15:46
Show Gist options
  • Select an option

  • Save visuve/c9b33005799ca3a44ff94252cc0e5134 to your computer and use it in GitHub Desktop.

Select an option

Save visuve/c9b33005799ca3a44ff94252cc0e5134 to your computer and use it in GitHub Desktop.
Swap endian
#include <iostream>
#include <algorithm>
#include <array>
template <typename T>
constexpr T swap_endian(T value)
{
union
{
T value;
std::array<uint8_t, sizeof(T)> bytes;
} swap;
swap.value = value;
std::reverse(swap.bytes.begin(), swap.bytes.end());
return swap.value;
}
int main()
{
int i;
do
{
std::cout << "Please enter an integer value: " << std::endl;
std::cin >> i;
printf("BE=%08x\n", i);
printf("LE=%08x\n", swap_endian<int32_t>(i));
std::cout << std::endl;
} while (i != 'x');
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment