Crunch
A Message Definition Language for Getting Things Right
Loading...
Searching...
No Matches
crunch_endian.hpp
1#pragma once
2
3#include <algorithm>
4#include <array>
5#include <bit>
6#include <concepts>
7#include <cstdint>
8#include <type_traits>
9
10namespace Crunch {
11
19template <typename T>
20 requires std::integral<T> || std::is_enum_v<T> || std::floating_point<T>
21[[nodiscard]] constexpr T LittleEndian(T value) noexcept {
22 if constexpr (std::endian::native == std::endian::little) {
23 return value;
24 } else if constexpr (std::integral<T>) {
25 return std::byteswap(value);
26 } else if constexpr (std::is_enum_v<T>) {
27 using U = std::underlying_type_t<T>;
28 return static_cast<T>(std::byteswap(static_cast<U>(value)));
29 } else {
30 // Floating point
31 auto bits = std::bit_cast<std::array<std::byte, sizeof(T)>>(value);
32 std::ranges::reverse(bits);
33 return std::bit_cast<T>(bits);
34 }
35}
36
37} // namespace Crunch
The public API for Crunch.
Definition: crunch_endian.hpp:10
constexpr T LittleEndian(T value) noexcept
Converts a value to/from Little Endian byte order.
Definition: crunch_endian.hpp:21