From 9191117120e9ba6911d152c7772d4566728cebcd Mon Sep 17 00:00:00 2001 From: Martchus Date: Tue, 20 Jun 2023 13:35:01 +0200 Subject: [PATCH] Fix binary conversion functions for big endian systems The code was broken on big endian systems by 07e95468555501837b7798c38b188fd20d57e89e. When doing an explicit swap one must distinguish the endianness the code runs on. --- conversion/binaryconversionprivate.h | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-) diff --git a/conversion/binaryconversionprivate.h b/conversion/binaryconversionprivate.h index 0b92001..01eed83 100644 --- a/conversion/binaryconversionprivate.h +++ b/conversion/binaryconversionprivate.h @@ -1,7 +1,16 @@ +// assert that CONVERSION_UTILITIES_BINARY_CONVERSION_INTERNAL is defined; a value of: +// - 0 means to define functions for BE namespace +// - 1 means to define functions for LE namespace #ifndef CONVERSION_UTILITIES_BINARY_CONVERSION_INTERNAL #error "Do not include binaryconversionprivate.h directly." #else +// define macro if swapping byte order is required +#if (CONVERSION_UTILITIES_BINARY_CONVERSION_INTERNAL == 0 && defined(CONVERSION_UTILITIES_BYTE_ORDER_LITTLE_ENDIAN)) \ + || (CONVERSION_UTILITIES_BINARY_CONVERSION_INTERNAL == 1 && defined(CONVERSION_UTILITIES_BYTE_ORDER_BIG_ENDIAN)) +#define CONVERSION_UTILITIES_BINARY_CONVERSION_INTERNAL_NEEDS_SWAP +#endif + // disable warnings about sign conversions when using GCC or Clang #ifdef __GNUC__ #pragma GCC diagnostic push @@ -144,7 +153,7 @@ template > * = nullptr> CPP_UTILIT { auto dst = T(); std::memcpy(&dst, value, sizeof(T)); -#if CONVERSION_UTILITIES_BINARY_CONVERSION_INTERNAL == 0 +#ifdef CONVERSION_UTILITIES_BINARY_CONVERSION_INTERNAL_NEEDS_SWAP dst = swapOrder(dst); #endif return dst; @@ -176,7 +185,7 @@ CPP_UTILITIES_EXPORT inline void getBytes24(std::uint32_t value, char *outputbuf */ template > * = nullptr> CPP_UTILITIES_EXPORT inline void getBytes(T value, char *outputbuffer) { -#if CONVERSION_UTILITIES_BINARY_CONVERSION_INTERNAL == 0 +#ifdef CONVERSION_UTILITIES_BINARY_CONVERSION_INTERNAL_NEEDS_SWAP value = swapOrder(value); #endif std::memcpy(outputbuffer, &value, sizeof(T)); @@ -206,4 +215,6 @@ CPP_UTILITIES_EXPORT inline void getBytes(double value, char *outputbuffer) #pragma GCC diagnostic pop #endif +#undef CONVERSION_UTILITIES_BINARY_CONVERSION_INTERNAL_NEEDS_SWAP + #endif // CONVERSION_UTILITIES_BINARY_CONVERSION_INTERNAL