Binary Serialize
Loading...
Searching...
No Matches
byteswap.hpp
Go to the documentation of this file.
1
18#ifndef BYTESWAP_HPP_INCLUDED
19#define BYTESWAP_HPP_INCLUDED
20
21#include <concepts> // std::integral concept
22#include <bit> // std::bit_cast
23#include <array>
24#include <cstddef> // std::byte
25#include <algorithm> // std::ranges::reverse
26
27namespace chops {
28
40template<std::integral T>
41constexpr T byteswap(T value) noexcept {
42 if constexpr (sizeof(T) == 1u) {
43 return value;
44 }
45 static_assert(std::has_unique_object_representations_v<T>,
46 "T may not have padding bits");
47 auto value_representation = std::bit_cast<std::array<std::byte, sizeof(T)>>(value);
48 std::ranges::reverse(value_representation);
49 return std::bit_cast<T>(value_representation);
50}
51
52} // end namespace
53
54#endif
55
constexpr T byteswap(T value) noexcept
Perform an in-place byte swap on an integral type (if size of the type is greater than one).
Definition byteswap.hpp:41