Circular shift on binary representation of an integer by k positions

Given a positive integer n and k, perform circular shift on binary representation 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 = 127 (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 –
 

Download   Run Code

Output:

No Shift    00000000000000000000000001111111
Left Shift  00000000000000000000001111111000
Right Shift 11100000000000000000000000001111

 
1 Star2 Stars3 Stars4 Stars5 Stars (1 votes, average: 5.00 out of 5)

Loading...

Thanks for reading.

Please use our online compiler to post code in comments. To contribute, get in touch with us.
Like us? Please spread the word and help us grow. Happy coding 🙂
 


Leave a Reply

avatar
  Subscribe  
Notify of