Reverse bits of the given number, and return new number

Reverse bits of the given number, and return new number

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
#!/usr/bin/env python3

# Function to reverse bits of the given number and return new number
def reverse_bits(n):
    rev = 0

    # traversing bits of 'n' from the right
    while (n > 0) :

        # bitwise left shift 'rev' by 1
        rev = rev << 1

        # if current bit is '1'
        if (n & 1 == 1) :
            rev = rev ^ 1

        # bitwise right shift 'n' by 1
        n = n >> 1


    # required number
    return rev