summaryrefslogtreecommitdiffstats
path: root/main.c
diff options
context:
space:
mode:
Diffstat (limited to 'main.c')
-rw-r--r--main.c35
1 files changed, 35 insertions, 0 deletions
diff --git a/main.c b/main.c
new file mode 100644
index 0000000..3daed9c
--- /dev/null
+++ b/main.c
@@ -0,0 +1,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;
+}