From c4a38865040111bd79458afd8a60d80dd011c3e8 Mon Sep 17 00:00:00 2001 From: Bruno BELANYI Date: Mon, 21 Nov 2022 17:03:27 +0100 Subject: [PATCH] c: ex3: add solution --- c/ex3.c | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 c/ex3.c diff --git a/c/ex3.c b/c/ex3.c new file mode 100644 index 0000000..84ff9a3 --- /dev/null +++ b/c/ex3.c @@ -0,0 +1,32 @@ +#include +#include + +static unsigned char reverse_byte(unsigned char c) { + unsigned char res = 0; + for (size_t i = 0; i < CHAR_BIT; ++i) { + unsigned char bit = (c & (1 << i)); + res |= bit << (CHAR_BIT - i - 1); + } + return res; +} + +static void swap_bytes(unsigned char* lhs, unsigned char* rhs) { + unsigned char tmp = *lhs; + *lhs = *rhs; + *rhs = tmp; +} + +void reverse_bytes(unsigned char* buf, size_t n) { + if (!buf || !n) + return; + + // No need to worry about applying reverse_byte twice in the middle by + // mistake if done in a preliminary pass + for (size_t i = 0; i < n; ++i) { + buf[i] = reverse_byte(buf[i]); + } + + for (size_t i = 0; i < ((n + 1) / 2); ++i) { + swap_bytes(&buf[i], &buf[n - 1 - i]); + } +}