Implementing a Bit Rotate Function - C Operator

C examples for Operator:Bit Operator

Description

Implementing a Bit Rotate Function

Demo Code

#include <stdio.h>
int rotate(int value, int n) {
   int result, bits;
   // scale down the shift count to a defined range
   if (n > 0)// w  ww. j  a v a 2  s .co m
      n = n % 32;
   else
      n = -(-n % 32);

   if (n == 0) {
      result = value;
   }
   else if (n > 0) {
      // shall left rotate
      bits = value >> (32 - n);
      result = value << n | bits;
   }
   else {
      // shall right rotate
      n = -n;
      bits = value << (32 - n);
      result = value >> n | bits;
   }
   return result;
}

int main(void) {
   unsigned int w1 = 0xabcdef00u, w2 = 0xffff1122u;

   printf("%x\n", rotate(w1, 8));
   printf("%x\n", rotate(w1, -16));
   printf("%x\n", rotate(w2, 4));
   printf("%x\n", rotate(w2, -2));
   printf("%x\n", rotate(w1, 0));
   printf("%x\n", rotate(w1, 44));

   return 0;
}

Result


Related Tutorials