Cyclic shifts of integer N by another integer m

Given an integer N represented as a binary representation of X = 16 bits. We are also given a number ‘m’ and a character c which is either L or R. The task is to determine a number M that is generated after cyclically shifting the binary representation of N by m positions either left if c = L or right if c = R.


Input : N = 7881, m = 5, c = L
Output : 55587
N in binary is 0001 1110 1100 1001 and shifting it left by 5 positions, it becomes 1101 1001 0010 0011 which in the decimal system is 55587.

Input : N = 7881, m = 3, c = R
Output : 9177
N in binary is 0001 1110 1100 1001 and shifted 3 positions to right, it becomes 0010 0011 1101 1001 which in the decimal system is 9177.


To solve the problem mentioned above we observe that we have to right shift the number by m if the char is R, else we will do a left shift by m if the char is L where left shifts is equivalent to multiplying a number by 2, right shifts is equivalent to dividing a number by 2.

Below is the implementation of the above approach:





# Python implementation to make 
# Cyclic shifts of integer N by another integer m
def Count(N, count, turn):
    # Convert N into hexadecimal number and
    # remove the initial zeros in it
    N = hex(int(N)).split('x')[-1]
    # Convert hexadecimal term binary
    # string of length = 16 with padded 0s
    S = ( bin(int(N, 16))[2:] ).zfill(16)
    # rotate the string by a specific count
    if(turn == 'R'):
        S = (S[16 - int(count) : ] + S[0 : 16 - int(count)])
        S = (S[int(count) : ] + S[0 : int(count)])
    # Convert the rotated binary string
    # in decimal form, here 2 means in binary form.
    print(int(S, 2))
# driver code 
N = 7881
count = 5
turn = 'L'
Count(N, count, turn)




Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using or mail your article to See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.

Improved By : nidhi_biet

Article Tags :
Practice Tags :

Be the First to upvote.

Please write to us at to report any issue with the above content.