Rotate bits of a number

Bit Rotation: A rotation (or circular shift) is an operation similar to shift except that the bits that fall off at one end are put back to the other end.

In left rotation, the bits that fall off at left end are put back at right end.

In right rotation, the bits that fall off at right end are put back at left end.

Example:
Let n is stored using 8 bits. Left rotation of n = 11100101 by 3 makes n = 00101111 (Left shifted by 3 and first 3 bits are put back in last ). If n is stored using 16 bits or 32 bits then left rotation of n (000…11100101) becomes 00..0011100101000.
Right rotation of n = 11100101 by 3 makes n = 10111100 (Right shifted by 3 and last 3 bits are put back in first ) if n is stored using 8 bits. If n is stored using 16 bits or 32 bits then right rotation of n (000…11100101) by 3 becomes 101000..0011100.

#include<stdio.h>
#define INT_BITS 32

/*Function to left rotate n by d bits*/
int leftRotate(int n, unsigned int d)
{
   /* In n<<d, last d bits are 0. To put first 3 bits of n at 
     last, do bitwise or of n<<d with n >>(INT_BITS - d) */
   return (n << d)|(n >> (INT_BITS - d));
}

/*Function to right rotate n by d bits*/
int rightRotate(int n, unsigned int d)
{
   /* In n>>d, first d bits are 0. To put last 3 bits of at 
     first, do bitwise or of n>>d with n <<(INT_BITS - d) */
   return (n >> d)|(n << (INT_BITS - d));
}

/* Driver program to test above functions */
int main()
{
  int n = 16;
  int d = 2;
  printf("Left Rotation of %d by %d is ", n, d);
  printf("%d", leftRotate(n, d));
  printf("\nRight Rotation of %d by %d is ", n, d);
  printf("%d", rightRotate(n, d));
  getchar();
} 

Please write comments if you find any bug in the above program or other ways to solve the same problem.





  • Mahesh Devkar

    its awesome…..
    Thank you…..:-)

  • abhishek08aug

    Here is the simple approach. Pick a bit and put it in the end:

     
    #include<stdio.h>
    #include<stdlib.h>
     
    char * bit_representation(unsigned int num) {
      char * bit_string = (char *)malloc(sizeof(char)*sizeof(unsigned int)*8+1);
      unsigned int i=1, j;
      for(i=i<<(sizeof(unsigned int)*8-1), j=0; i>0; i=i>>1, j++) {
        if(num&i) {
          *(bit_string+j)='1';
        } else {
          *(bit_string+j)='0';
        }
      }
      *(bit_string+j)='\0';
      return bit_string;
    }
    
    unsigned int rotate_bits(unsigned int num) {
      unsigned int rev_num = 0;
      unsigned int i, j=0x80000000, k;
      unsigned int bit_position=0;
      for(i=1; i!=0; i=i<<1, bit_position++) {
        if(num&i) {
          for(k=31; k>31-bit_position; k--) {
            j=j>>1;
          }
          rev_num = rev_num|j;
          j=0x80000000;
        }
      }
      return rev_num;
    }
    
    int main(){
      unsigned int i=1;
      printf("\nbit representation of unsigned integer: %u = %s and reversed bits: %s\n", i, bit_representation(i), bit_representation(rotate_bits(i)));
      i=32;
      printf("\nbit representation of unsigned integer: %u = %s and reversed bits: %s\n", i, bit_representation(i), bit_representation(rotate_bits(i)));
      return 0;
    }
     

    bit representation of unsigned integer: 1 = 00000000000000000000000000000001 and reversed bits: 10000000000000000000000000000000

    bit representation of unsigned integer: 32 = 00000000000000000000000000100000 and reversed bits: 00000100000000000000000000000000

    bit representation of unsigned integer: 1234567 = 00000000000100101101011010000111 and reversed bits: 11100001011010110100100000000000

    • abhishek08aug

      Oops I just reversed the bits 😮

      • gladiator

        Intelligent 😀

         
        /* Paste your code here (You may delete these lines if not writing code) */
         
  • Hanish

    It does not work for negative numbers. Because right shifting a negative number by x bits sets the last x bits of the number.
    Type casting of n to unsigned int is required in the function argument

  • Satish

    #include
    #include
    #define value(a)8*sizeof(a)
    void main()
    {
    int n=3;
    int a=8;
    char a1=8;
    clrscr();

    printf(” left rotates %d”,(a<>value(a)-n));
    printf(“\n\n Right rotates %d”,(a>>n)|(a<<value(a)-n));

    printf("\n\ncharacter left rotates %d",(a1<>value(a1)-n));
    printf(“\n\ncharacter Right rotates %d”,(a1>>n)|(a1<<value(a1)-n));

    getch() ;

    }

    this program automatic adjust the no. of byte block…

  • http://cracktheinterview.org/ vinay polisetti

    most elegant solution I have ever seen !!

  • abhishek

    This above approach works in following cases only:
    1. unsigned integer
    2. number to be rotated should occupy whole width of integer.

  • Suresh Paldia
     
    #include<stdio.h>
    void main()
    {
    	int x=67, y=35;
    	int a,b;
    	int result;
    	a=x/y;
    	b=y/x;
    	result = (x*(a) + y*(b));
    	result = result/(a+b);
    	printf("Greater of %d and %d is %d",x,y,result);	
    }
     
  • sunny321

    what happen if num is -ve

    • sunny

      plzzzz reply my query also

  • vaibhav

    this implementation has a problem.Take a number 27 ( 11011) and rotate it left by 2 digits, you will get 15(01111).So here you van not always take no of bit= 32.You will try to find the position of left most set bit and your INT_BITS will be equal to that value.

    • GeeksforGeeks

      @vaibhav: The program doesn’t return 15 for 27. We have added few more words to post to explain this.

      • Silent

        it does not work for negative numbers as negative numbers are filled with 1’s from the left..

    • sureshpaldia22

      You can have a modification in definition of INT_BITS to get the bits count of INT for your compiler.

      #define INT_BITS 8*sizeof(int)

      • http://graphics.stanford.edu/~seander/bithacks.html#OperationCounting Krishna Kishore
         
        /*we can find the left most set bit as */
        for ( int i = 0  ; n >> 1 ; i++ );
        /* The value of i would be the position of Left Most set bit. */