Skip to content

Commit 699c5fd

Browse files
committed
Implemented 32-bit version of the code for more flexibility
1 parent bdcee72 commit 699c5fd

File tree

1 file changed

+32
-33
lines changed

1 file changed

+32
-33
lines changed

chapter_2/exercise_2_08/rightrot.c

Lines changed: 32 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -1,48 +1,47 @@
1-
#include <math.h>
1+
#include <limits.h>
22
#include <stdio.h>
33

4-
void printbin(unsigned int x);
5-
unsigned int rightrot(unsigned int x, unsigned int n);
4+
/* Exercise 2.8: Write a function rightrot(x, n) that returns the value
5+
* of the integer x rotated to the right by n bit positions.
6+
*/
67

7-
int main(void) {
8-
// Using hexadecimal instead of binary literals (0b...) for C89/C99
9-
// compatibility 0xF5 = 0b11110101
10-
unsigned int x = 0xF5;
8+
void to_binary(unsigned short n) {
9+
unsigned long i = 0;
10+
int binary[32];
11+
printf("0b");
1112

12-
printbin(x);
13-
printbin(rightrot(x, 5));
13+
if (n == 0) {
14+
printf("0\n");
15+
return;
16+
}
1417

15-
return 0;
18+
while (i < sizeof(unsigned short) * CHAR_BIT) {
19+
binary[i++] = n % 2;
20+
n = n / 2;
21+
}
22+
for (int j = i - 1; j >= 0; j--) {
23+
printf("%d", binary[j]);
24+
}
25+
printf("\n");
1626
}
1727

18-
void printbin(unsigned int x) {
19-
unsigned int n = sizeof(unsigned int);
28+
unsigned short rightrot(unsigned short x, int n) {
29+
unsigned w = sizeof(unsigned short) * CHAR_BIT;
30+
n %= w;
2031

21-
printf("0b");
32+
return (x >> n) | (x << (w - n));
33+
}
2234

23-
int i;
24-
for (i = n * 8 - 1; i >= 0; --i) {
25-
(x & (unsigned int)pow(2, i)) ? putchar('1') : putchar('0');
26-
}
35+
int main(void) {
36+
unsigned short x;
37+
x = 55;
2738

28-
putchar('\n');
29-
}
39+
printf("x = %d -->", x);
40+
to_binary(x);
3041

31-
unsigned int rightrot(unsigned int x, unsigned int n) {
32-
unsigned int msb_1 = ~(~(unsigned)0 >> 1);
33-
34-
// Using unsigned int for i to match the unsigned n parameter
35-
// This prevents sign comparison warnings
36-
unsigned int i;
37-
for (i = 0; i < n; ++i) {
38-
if (x & 1) {
39-
x = (x >> 1) | msb_1;
40-
} else {
41-
x = (x >> 1);
42-
}
43-
}
42+
to_binary(rightrot(x, 3));
4443

45-
return x;
44+
return 0;
4645
}
4746

4847
// NOTE: The rightrot function rotate the entire unsigned int var and if we

0 commit comments

Comments
 (0)