Menu
Coddy logo textTech

Rotate bits of a number II

Lesson 13 of 17 in Coddy's Bit Manipulation course.

Alright! You've understood what rotation means. But rotation in this case can also be looked at by using shift operations. We can also say that rotating a binary number is just like performing shift operation on it but instead of discarding the bits we place them back in the number. Let's understand with an example-

Let's say we have (33)10 in a 8-bit computer. It will be stored as (00100001)2, if we let's say rotate it leftwards 3 times.

  •  Firstly we have left shifted the (33)10 3 times.
  • And to save the left out bits we have right shifted it 8-3 times. (8 is the number of bits the computer uses to place the number in memory)
  • Then we have done OR operation on x and y to get the rotated number.
x = 33<<300001000
y = 33>>500000001

x | y

00001001

Similarly we can do for right rotation-

  • Firstly we will shift (33)10 towards right 3 times and save that value in variable.
  • Then we left shift it (8-3) times and save that value in another variable.
  • Then by doing OR operation, we will get our rotated number.
x = 33 >> 300000100
y = 33 << 500100000

x | y

00100100

That's it! That's how we can rotate the bits of a binary number so easily just because of bit manipulations.

challenge icon

Challenge

Medium

Complete the function SumLeftRightRotation() to return the sum of value of left and right rotation of the given number. 

For instance, for number 20 after left rotation returns 40 and for right rotation it returns 10, so output will be 50, the sum of left and right rotations. 

Here, num represents the number and r represents the number of rotations.

Try it yourself

#define INT_BITS 32
using namespace std;

int SumLeftRightRotation(int num, int r) {
    // Write code here
}

All lessons in Bit Manipulation