-1

How do I rotate the bits of given number, input number of rotations, at runtime?

For example:

binary:    10000000000000000000000000001011
rotations: 3 times right
result:    01110000000000000000000000000001

Similarly:

binary     10000000000000000000000000001011
rotations: 4 times left
result:    00000000000000000000000010111000

Below is my code to swap, but I couldn't find the logic to rotate the bits.

#include<stdio.h>
int main()
{
    int num,bitleft,bitright,i,j;
    printf("enter ur number\n");
    scanf("%d",&num);

    for(i=31,j=0;i>j;i--,j++) 
    {
        bitleft=num>>i&1;  //storing bits in integer from left
        bitright=num>>j&1;  //storing bits in integer from right
        if(bitleft!=bitright) // checking if bits are not similarly
        {
            num=num^1<<i; // not similar then complement
            num=num^1<<j;

        }
    }
    printf("\n");

    for(j=31;j>=0;j--)  // loop to print swapped bits
    {
        if(num&1<<j)
            printf("1");
        else
            printf("0");
    } 
}
Drew McGowen
  • 11,471
  • 1
  • 31
  • 57
user3859409
  • 3
  • 1
  • 3

1 Answers1

2

Try this:

#include <iostream>

template <typename T>
T rol_(T value, int count) {
    return (value << count) | (value >> (sizeof(T)*CHAR_BIT - count));
}

template <typename T>
T ror_(T value, int count) {
    return (value >> count) | (value << (sizeof(T)*CHAR_BIT - count));
}

int main() {
    unsigned int a = 0x8000000B; // 10000000000000000000000000001011 in binary
    std::cout << "A = 0x" << std::hex << a << ", ror(A, 3) = 0x" << ror_(a, 3) << std::endl;
    std::cout << "A = 0x" << std::hex << a << ", rol(A, 3) = 0x" << rol_(a, 3) << std::endl;
    return 0;
}

Notes:

  • (value << count) in rol and (value >> count) in ror set the high bits in rol and the lower bits in ror. The other bits fall away.
  • (value >> (sizeof(T)*CHAR_BIT - count)) in rol and (value << (sizeof(T)*CHAR_BIT - count)) in ror set the bits that fall away in the previous operation.

Example (assuming types of 32bits):

binary:               10000000000000000000000000001011
rotations: 3 times right
(value >> 3):         00010000000000000000000000000001
(value << (32 - 3)):  01100000000000000000000000000000
------------------------------------------------------
                      01110000000000000000000000000001
NetVipeC
  • 4,402
  • 1
  • 17
  • 19