blob: 3daed9c0fbde3cb9ec52adbfef91da162cdbe56b (
plain)
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
|
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
/*
Exercise 2-8. Write a function rightrot(x,n)
that returns the value of the
(unsigned) integer x rotated to the right by n bit positions.
*/
unsigned rightrot(unsigned x, int n)
{
#ifndef AMD64
//right rotate assembly instruction is used if the arch is AMD64.
for (int i=0;i<n;++i)
asm("ror $1, %[x];" : "=r" (x) :[x] "0" (x) );
#else
//slow, but correct.
for (int i=0;i<n;++i)
{
/* If the lowest bit is 1, the highest bit needs to be set to 1 to simulate rotating */
if (x & 1){x = (x >> 1); x |= (1UL << ((sizeof(x) * CHAR_BIT)-1));}
/* if the lowest bit is 0, be don't need to rotate */
else{x = (x >> 1);}
}
#endif
return x;
}
int main(void)
{
printf("%u\n", rightrot(0xAAA,2147483647));
return 0;
}
|