From 2ab1ee34f9557ce8f5610595f72f358a8cc05978 Mon Sep 17 00:00:00 2001 From: Aryadev Chavali Date: Sun, 28 Apr 2024 22:31:41 +0530 Subject: [PATCH] Use byteswap to implement conversion to and from bytes Cleaner looking implementations --- lib/base.c | 30 ++++++++++-------------------- 1 file changed, 10 insertions(+), 20 deletions(-) diff --git a/lib/base.c b/lib/base.c index 2142039..8b5a617 100644 --- a/lib/base.c +++ b/lib/base.c @@ -29,39 +29,29 @@ word_t word_byteswap(const word_t w) hword_t convert_bytes_to_hword(const byte_t *bytes) { hword_t h = 0; - if (LITTLE_ENDIAN) - memcpy(&h, bytes, HWORD_SIZE); - else - for (size_t i = 0; i < HWORD_SIZE; ++i) - h |= ((hword_t)(bytes[i]) << (8 * i)); + memcpy(&h, bytes, HWORD_SIZE); + if (!LITTLE_ENDIAN) + h = hword_byteswap(h); return h; } word_t convert_bytes_to_word(const byte_t *bytes) { word_t h = 0; - if (LITTLE_ENDIAN) - memcpy(&h, bytes, WORD_SIZE); - else - for (size_t i = 0; i < WORD_SIZE; ++i) - h |= ((word_t)(bytes[i]) << (8 * i)); + memcpy(&h, bytes, WORD_SIZE); + if (!LITTLE_ENDIAN) + h = word_byteswap(h); return h; } void convert_hword_to_bytes(hword_t w, byte_t *bytes) { - if (LITTLE_ENDIAN) - memcpy(bytes, &w, HWORD_SIZE); - else - for (size_t i = 0; i < HWORD_SIZE; ++i) - bytes[i] = WORD_NTH_BYTE(w, i); + hword_t h = LITTLE_ENDIAN ? w : hword_byteswap(w); + memcpy(bytes, &h, HWORD_SIZE); } void convert_word_to_bytes(word_t w, byte_t *bytes) { - if (LITTLE_ENDIAN) - memcpy(bytes, &w, WORD_SIZE); - else - for (size_t i = 0; i < WORD_SIZE; ++i) - bytes[i] = WORD_NTH_BYTE(w, i); + word_t h = LITTLE_ENDIAN ? w : word_byteswap(w); + memcpy(bytes, &h, WORD_SIZE); }