diff options
author | Gentoo <installgentoo@endianness.com> | 2021-03-27 10:16:47 +1100 |
---|---|---|
committer | Gentoo <installgentoo@endianness.com> | 2021-03-27 10:16:47 +1100 |
commit | 4eb6e5e4258bcfac2f1980ec8557914f792203b4 (patch) | |
tree | 8f08d226576155cfdaca21f87d6aecfd8225a795 /main.c | |
download | rightrotate-master.tar.gz rightrotate-master.tar.bz2 rightrotate-master.zip |
Diffstat (limited to 'main.c')
-rw-r--r-- | main.c | 35 |
1 files changed, 35 insertions, 0 deletions
@@ -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; +} |