From 1740db2c545a9170e00d478aec30b212bfde4228 Mon Sep 17 00:00:00 2001 From: Geoffrey Merck Date: Sun, 26 Dec 2021 17:46:45 +0100 Subject: [PATCH] Add swap endian --- Utils.cpp | 1 - Utils.h | 21 +++++++++++++++++++++ 2 files changed, 21 insertions(+), 1 deletion(-) diff --git a/Utils.cpp b/Utils.cpp index 46639cf..43f0c63 100644 --- a/Utils.cpp +++ b/Utils.cpp @@ -425,4 +425,3 @@ void CUtils::truncateFile(const std::string& fileName) if(file.is_open()) file.close(); } - diff --git a/Utils.h b/Utils.h index fd1f445..61fa0fb 100644 --- a/Utils.h +++ b/Utils.h @@ -17,6 +17,8 @@ #include #include #include +#include +#include enum TRISTATE { STATE_FALSE, @@ -45,4 +47,23 @@ public: static void ReplaceChar(std::string &str, char from, char to); static time_t parseTime(const std::string str); static void truncateFile(const std::string& fileName); + + template + static T swap_endian(T u) + { + static_assert (CHAR_BIT == 8, "CHAR_BIT != 8"); + + union + { + T u; + unsigned char u8[sizeof(T)]; + } source, dest; + + source.u = u; + + for (size_t k = 0; k < sizeof(T); k++) + dest.u8[k] = source.u8[sizeof(T) - k - 1]; + + return dest.u; + } };