C++ program to Rotate bits

Hey there! In this tutorial, we will learn how to rotate bits of a number using the C++ programming language. Here is what rotation means:
Suppose there is a number 13 and we want to left rotate its bits by 2 places.

13 is 00001101 in binary.
Left rotating bits by 2 places gives
Answer is 00110100 which is 52 in decimal.

Let us see how we can do this.

Use of bitwise operators

For achieving this we will use some bitset operators:

  • >>(Right Shift): Shifts the bits of a number towards the right by given places.
12>>2
//shifts digits of 12(00001100) by 2 places
//00000011 is the answer
  • <<(Left Shift): Shifts the bits of a number towards the left by given places.
12<<2
//shifts digits of 12(00001100) by 2 places
//00110000 is the answer
  • |(Bitwise OR): Performs OR operation on bits.
00000101 | 00001100
//00001101 is the answer

Implementation

  • First, shift the bits of the given number by the given places(p).
  • We need to take into account the first/last ‘p’ bits which get lost due to shifting but we need at the end/beginning to complete rotation so we use bitwise OR operator.
  • Bitwise OR it with right-shifted(to recover first ‘p’ bits) or left-shifted(to recover last ‘p’ bits) the given number by (8-p) places.

Below is the code implementing left rotate and right rotate:

#include <bits/stdc++.h>
using namespace std;

int main() {
    int number = 13;//00001101
    int p = 2;
    bitset <8> binary(number);
    //converting it in 8 places binary

        p=p%8; //rotating more than 8 times is repetition
    // to_ullong() converts binary into unsigned long long 
    cout << ((binary<<p)|(binary>>(8-p))).to_ullong() << endl;
    //left shift gives 00110100
    cout << ((binary>>p)|(binary<<(8-p))).to_ullong() << endl;
    //right shift gives 01000011
    
  return 0;
}

Output:

52
67

That’s it. Hope you understood.

Leave a Reply

Your email address will not be published. Required fields are marked *