|
1 | | -#include <math.h> |
| 1 | +#include <limits.h> |
2 | 2 | #include <stdio.h> |
3 | 3 |
|
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 | + */ |
6 | 7 |
|
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"); |
11 | 12 |
|
12 | | - printbin(x); |
13 | | - printbin(rightrot(x, 5)); |
| 13 | + if (n == 0) { |
| 14 | + printf("0\n"); |
| 15 | + return; |
| 16 | + } |
14 | 17 |
|
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"); |
16 | 26 | } |
17 | 27 |
|
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; |
20 | 31 |
|
21 | | - printf("0b"); |
| 32 | + return (x >> n) | (x << (w - n)); |
| 33 | +} |
22 | 34 |
|
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; |
27 | 38 |
|
28 | | - putchar('\n'); |
29 | | -} |
| 39 | + printf("x = %d -->", x); |
| 40 | + to_binary(x); |
30 | 41 |
|
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)); |
44 | 43 |
|
45 | | - return x; |
| 44 | + return 0; |
46 | 45 | } |
47 | 46 |
|
48 | 47 | // NOTE: The rightrot function rotate the entire unsigned int var and if we |
|
0 commit comments