Created
August 2, 2018 10:58
-
-
Save sikanrong/f3b94dba6fdad717038147c226e83a89 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//https://www.geeksforgeeks.org/rotate-bits-of-an-integer/ | |
/* | |
* rotate_bits.c | |
* | |
* Created on: Aug 2, 2018 | |
* Author: sikanrong | |
*/ | |
#include <stdio.h> | |
#include <stdint.h> | |
int main(){ | |
//unsigned 8-bit integer, alias for char | |
uint8_t n = 0; | |
int r; | |
char d; | |
printf("Direction to rotate (l or r): "); | |
scanf("%c", &d); | |
printf("Integer upon which to perform rotation: "); | |
scanf("%u", &n); | |
printf("Positions to rotate (integer): "); | |
scanf("%i", &r); | |
while(r){ | |
if(d == 'r'){ | |
int mask = 1; | |
int bit = (n & mask); | |
n = n >> 1; | |
n += (bit << 7); | |
}else{ | |
int mask = 1 << 7; | |
//is leftmost bit set? | |
int bit = (n & mask); | |
n = (n << 1); | |
n += (bit >> 7); | |
} | |
r--; //one less rotation | |
} | |
printf("Rotated value: %u", n); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment