From 9495b0a23eb3026dd2c0c8b20f2c506808e43f44 Mon Sep 17 00:00:00 2001 From: Intel A80486DX2-66 Date: Sun, 19 May 2024 13:58:26 +0300 Subject: [PATCH] fwrite_le.*: refactor --- include/fwrite_le.h | 5 +++++ src/fwrite_le.c | 18 +++++------------- 2 files changed, 10 insertions(+), 13 deletions(-) diff --git a/include/fwrite_le.h b/include/fwrite_le.h index 82395e8..ec04e87 100644 --- a/include/fwrite_le.h +++ b/include/fwrite_le.h @@ -12,6 +12,11 @@ #define DETECTED_BIG_ENDIAN 1 #define UNSUPPORTED_ENDIANNESS -1 +#define ORDER_NATIVE_U32 0x01234567 +#define ORDER_LITTLE_ENDIAN_S4 "\x67\x45\x23\x01" +#define ORDER_BIG_ENDIAN_S4 "\x01\x23\x45\x67" +#define ifeq_u32_ret(lhs, rhs, value) if (!memcmp(lhs, rhs, 4)) return value; + int detect_endianness(void); size_t fwrite_le(void* ptr, size_t size, size_t count, FILE* stream); void reorder_le_be( diff --git a/src/fwrite_le.c b/src/fwrite_le.c index 1c56322..20cc7fb 100644 --- a/src/fwrite_le.c +++ b/src/fwrite_le.c @@ -1,19 +1,11 @@ #include "fwrite_le.h" int detect_endianness(void) { - volatile uint32_t i = 0x01234567; - uint8_t* bytes = (uint8_t*)(&i); - if (bytes[0] == 0x01 && - bytes[1] == 0x23 && - bytes[2] == 0x45 && - bytes[3] == 0x67) - return DETECTED_BIG_ENDIAN; - else if ( - bytes[0] == 0x67 && - bytes[1] == 0x45 && - bytes[2] == 0x23 && - bytes[3] == 0x01) - return DETECTED_LITTLE_ENDIAN; + volatile uint32_t native_order_value = ORDER_NATIVE_U32; + uint8_t* as_bytes = (uint8_t*)&native_order_value; + + ifeq_u32_ret(as_bytes, ORDER_LITTLE_ENDIAN_S4, DETECTED_LITTLE_ENDIAN); + ifeq_u32_ret(as_bytes, ORDER_BIG_ENDIAN_S4, DETECTED_BIG_ENDIAN ); return UNSUPPORTED_ENDIANNESS; }