MCPcopy Create free account
hub / github.com/andreasfertig/programming-with-cpp20 / ByteSwap

Function ByteSwap

12.08-byteSwap1/main.cpp:30–49  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

28
29template<std::integral T>
30constexpr T ByteSwap(T value)
31{
32 if constexpr(std::endian::native == std::endian::big ||
33 (sizeof(value) == 1)) {
34 return value;
35 } else {
36 if(std::is_constant_evaluated()) {
37 return ReverseBytes(value);
38 } else {
39 if constexpr(std::same_as<T, uint64_t>) {
40 return htonl(value >> 32) |
41 (static_cast<uint64_t>(htonl(value)) << 32);
42 } else if constexpr(std::same_as<T, uint32_t>) {
43 return htonl(value);
44 } else if constexpr(std::same_as<T, uint16_t>) {
45 return htons(value);
46 }
47 }
48 }
49}
50
51static_assert(ByteSwap(uint64_t(0x123456789ABCDEF0)) ==
52 0xF0DEBC9A78563412);

Callers 2

main.cppFile · 0.70
mainFunction · 0.70

Calls 1

ReverseBytesFunction · 0.70

Tested by

no test coverage detected