Skip to content

Instantly share code, notes, and snippets.

@sikanrong
Created August 2, 2018 10:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sikanrong/f3b94dba6fdad717038147c226e83a89 to your computer and use it in GitHub Desktop.
Save sikanrong/f3b94dba6fdad717038147c226e83a89 to your computer and use it in GitHub Desktop.
//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