Python program to reverse bits of a positive integer number?

PythonProgrammingServer Side Programming

First convert number into binary using bin() function. Then skip the first two character of binary representation because bin() appends 0b as a prefix in a binary representation of the number and reverse the remaining part. From also character and reverse it till second last character from left. Convert a reversed binary string into integer.

Algorithm

integernumber(n,bit_size)
/* n is the number and bit_size is the bitsize  */
Step 1: first convert number into binary .
Step 2: skip the first two characters of binary representation string and reverse.
Step 3: remaining string and then append 0’s after it.
Step 4: from the last character and reverse it until second last character from the left.
Step 5: converts reversed binary string into an integer.

Example Code

# Python Program reverse bits of positive integer number
defintegernumber(n,bit_size):
   bin_number = bin(n)
   reverse_number = bin_number[-1:1:-1]
   reverse_number = reverse_number + (bit_size - len(reverse_number))*'0'
   print ("Reverse Bits ::>",int(reverse_number,2))
# Driver program
if __name__ == "__main__":
   n = int(input("Enter Number ::>"))
   bit_size = int(input("Enter Bit Size ::>")) 
   integernumber(n,bit_size)

output

Enter Number ::>1
Enter Bit Size ::>32
Reverse Bits ::> 2147483648

Enter Number ::>2147483648
Enter Bit Size ::>32
Reverse Bits ::> 1
raja
Published on 25-Sep-2018 16:19:47
Advertisements