Reverse bits of a positive integer in Python

Python Methods and Functions

Examples:

 Input: n = 1, bitSize = 32 Output: 2147483648 On a machine with size of bit as 32. Reverse of 0 .... 001 is 100 .... 0. Input: n = 2147483648, bitSize = 32 Output: 1 

We can solve this problem quickly in Python. The approach is very simple,

  1. Convert an integer to its binary representation using the

    # Function to invert positive bits
    # integer

     

    def reverseBits (num, bitSize):

     

    # convert number to binary

    # the output will look like bin (10) = & # 39; 0b10101 & # 39;

    binary = bin (num)

     

    # skip type first two characters of binary

    # string and back

    # remaining line and adding zeros

    # after that. binary file [-1: 1: -1] - & gt; start

    # from the last character and rotate it to

    # second last character from the left

    reverse = binary [ - 1 : 1 : - 1 ]

    reverse = reverse + (bitSize - len (reverse)) * ' 0'

      

    # converts a flipped binary string to an integer

    print int (reverse, 2 )

     
    # Driver program

    if __ name__ = = "__ main __" :

    num = 1

    bitSize = 32

      reverseBits (num, bitSize)

    Output:

     2147483648 




Tutorials