Given a positive n and k, perform on of it by k positions.

Circular shift can be of two types –

1. Left circular shift (moving the final bit to the first position, while shifting all other bits to the next position)

2. Right circular shift (moving the first bit to the last position, while shifting all other bits to the previous position)

For example,

Input:
N = 12 (00000000000000000000000001111111)
shift = 3

Output:
Left Shift  00000000000000000000001111111000
Right Shift 11100000000000000000000000001111

The idea is to perform a normal bitwise left or right shift by first isolating the sequence of k-bits from the right side or left side respectively. Finally return the bitwise OR of shifted number with isolated bits at their correct position.

For example, consider n = 127 which is 00000000000000000000000001111111

Circular Right shift by 3 –

1. Isolate the 3-bits from the right

00000000000000000000000001111111

2. Right shift by 3

00000000000000000000000001111111
00000000000000000000000000001111

3. OR with isolated bits

00000000000000000000000000001111
11100000000000000000000000000000
————————————————————————————————
11100000000000000000000000001111

Circular Left shift by 3 –

1. Isolate the 3-bits from the left

00000000000000000000000001111111

2. Left shift by 3

00000000000000000000000001111111
00000000000000000000001111111000

3. OR with isolated bits

00000000000000000000001111111000
00000000000000000000000000000000
————————————————————————————————
00000000000000000000001111111000

C++ implementation –

Output:

No Shift    00000000000000000000000001111111
Left Shift  00000000000000000000001111111000
Right Shift 11100000000000000000000000001111