Reverse Bits Algo

40

# Python code to implement the approach
 
# Function to find the reverse of the number
def reverse_bits(number, bit_size):   
    # for example, if bitSize is 32   
    # then after 1 << bitSize we will get
    # a 1 in 33-th bit position   
    # bin(1 << bitSize) looks like
    # '0b100000000000000000000000000000000'   
    # so to get all 1 in each 32 bit positions,
    # we need to subtract 1 from (1 << bitSize)
    max_value = (1 << bit_size) - 1
     
    # it is the maximum value for unsigned int32
    # then just subtract your number from the maximum
    return max_value - number
 
if __name__ == "__main__":
    # for example we can get the number 56
    num = 156
     
    # chose a binary size which we want to reverse
    size = 32
    print(reverse_bits(num, size))

Comments

Submit
0 Comments