I'm following KnR. This is excercise 2-8. It says to create a function to rotate a number to the right by some number of bits.
The answer i came up with 'seems' to do the job, and in two lines. However, i was checking for other methods online. This SO answer talks about a shifting each bit one by one. What is wrong if i shift in bulk (as in my code below )? is there something i'm missing ?
#include <stdio.h>
/* Rotate number 'num' to the right by 'rbits' bits */
int RotRight(unsigned int num,int rbits){
unsigned int mask = num << ((sizeof(int)*8)-rbits);
return (num>>rbits)|mask;
}
EDIT : To accommodate what i'v learnt from the comments , here is an edited version of the above code. Does this look good ?
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
int RotRight(int num,int rbits){
if(num<0) {
fprintf(stderr,"Rotating negative numbers is undefined\n");
exit(EXIT_FAILURE);
}
if(rbits >= sizeof(int)*CHAR_BIT) rbits = rbits % (sizeof(int)*CHAR_BIT);
if(rbits<=0) return num; // rbit range should be 0 to (bitwidth - 1)
unsigned int mask = num << ((sizeof(int)*CHAR_BIT)-rbits);
return (num>>rbits)|mask;
}