From 699c5fd4a0a90c30be618e483507b29d5389cd1f Mon Sep 17 00:00:00 2001 From: Ayush Hegde Date: Mon, 15 Dec 2025 16:40:30 +0530 Subject: [PATCH] Implemented 32-bit version of the code for more flexibility --- chapter_2/exercise_2_08/rightrot.c | 65 +++++++++++++++--------------- 1 file changed, 32 insertions(+), 33 deletions(-) diff --git a/chapter_2/exercise_2_08/rightrot.c b/chapter_2/exercise_2_08/rightrot.c index 5e7c1b5..f0bd851 100644 --- a/chapter_2/exercise_2_08/rightrot.c +++ b/chapter_2/exercise_2_08/rightrot.c @@ -1,48 +1,47 @@ -#include +#include #include -void printbin(unsigned int x); -unsigned int rightrot(unsigned int x, unsigned int n); +/* Exercise 2.8: Write a function rightrot(x, n) that returns the value + * of the integer x rotated to the right by n bit positions. + */ -int main(void) { - // Using hexadecimal instead of binary literals (0b...) for C89/C99 - // compatibility 0xF5 = 0b11110101 - unsigned int x = 0xF5; +void to_binary(unsigned short n) { + unsigned long i = 0; + int binary[32]; + printf("0b"); - printbin(x); - printbin(rightrot(x, 5)); + if (n == 0) { + printf("0\n"); + return; + } - return 0; + while (i < sizeof(unsigned short) * CHAR_BIT) { + binary[i++] = n % 2; + n = n / 2; + } + for (int j = i - 1; j >= 0; j--) { + printf("%d", binary[j]); + } + printf("\n"); } -void printbin(unsigned int x) { - unsigned int n = sizeof(unsigned int); +unsigned short rightrot(unsigned short x, int n) { + unsigned w = sizeof(unsigned short) * CHAR_BIT; + n %= w; - printf("0b"); + return (x >> n) | (x << (w - n)); +} - int i; - for (i = n * 8 - 1; i >= 0; --i) { - (x & (unsigned int)pow(2, i)) ? putchar('1') : putchar('0'); - } +int main(void) { + unsigned short x; + x = 55; - putchar('\n'); -} + printf("x = %d -->", x); + to_binary(x); -unsigned int rightrot(unsigned int x, unsigned int n) { - unsigned int msb_1 = ~(~(unsigned)0 >> 1); - - // Using unsigned int for i to match the unsigned n parameter - // This prevents sign comparison warnings - unsigned int i; - for (i = 0; i < n; ++i) { - if (x & 1) { - x = (x >> 1) | msb_1; - } else { - x = (x >> 1); - } - } + to_binary(rightrot(x, 3)); - return x; + return 0; } // NOTE: The rightrot function rotate the entire unsigned int var and if we