From a61cf61fd16f49a546987210b85db34769ff49ea Mon Sep 17 00:00:00 2001 From: Bananymous Date: Mon, 20 Mar 2023 19:45:09 +0200 Subject: [PATCH] BAN: Add wrappers for little/big endian numbers --- BAN/include/BAN/Endianness.h | 45 ++++++++++++++++++++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 BAN/include/BAN/Endianness.h diff --git a/BAN/include/BAN/Endianness.h b/BAN/include/BAN/Endianness.h new file mode 100644 index 0000000000..a28d2b4960 --- /dev/null +++ b/BAN/include/BAN/Endianness.h @@ -0,0 +1,45 @@ +#pragma once + +#include + +#include + +namespace BAN +{ + + template + struct LittleEndian + { + constexpr operator T() const + { +#if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__ + return raw; +#else + T result { 0 }; + for (size_t i = 0; i < sizeof(T); i++) + result = (result << 8) | ((raw >> (sizeof(T) - i - 1) * 8) & 0xFF); + return result; +#endif + } + T raw; + }; + + template + struct BigEndian + { + constexpr operator T() const + { +#if __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__ + return raw; +#else + T result { 0 }; + for (size_t i = 0; i < sizeof(T); i++) + result = (result << 8) | ((raw >> (i * 8)) & 0xFF); + return result; +#endif + } + private: + T raw; + }; + +} \ No newline at end of file