-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathprog.12.4.c
45 lines (35 loc) · 893 Bytes
/
prog.12.4.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
// Program to illustrate rotation of integers
#include <stdio.h>
int main (void)
{
unsigned int w1 = 0xabcdef00u, w2 = 0xffff1122u;
unsigned int rotate (unsigned int value, int n);
printf ("%x\n", rotate (w1, 8));
printf ("%x\n", rotate (w1, -16));
printf ("%x\n", rotate (w2, 4));
printf ("%x\n", rotate (w2, -2));
printf ("%x\n", rotate (w1, 0));
printf ("%x\n", rotate (w1, 44));
return 0;
}
// Function to rotate an unsigned int left or right
unsigned int rotate (unsigned int value, int n)
{
unsigned int result, bits;
// scale down the shift count to a defined range
if ( n > 0 )
n = n % 32;
else
n = -(-n % 32);
if ( n == 0 )
result = value;
else if ( n > 0 ) { // left rotate
bits = value >> (32 - n);
result = value << n | bits;
} else { // right rotate
n = -n;
bits = value << (32 - n);
result = value >> n | bits;
}
return result;
}