Created
December 7, 2021 15:46
-
-
Save visuve/c9b33005799ca3a44ff94252cc0e5134 to your computer and use it in GitHub Desktop.
Swap endian
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 <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