// JavaScript program to
// reverse bits of a number
// function to reverse bits of a number
function reverseBits(n)
{
let rev = 0;
// traversing bits of 'n'
// from the right
while (n > 0)
{
// bitwise left shift
// 'rev' by 1
rev <<= 1;
// if current bit is '1'
if ((n & 1) == 1)
rev ^= 1;
// bitwise right shift
//'n' by 1
n >>= 1;
}
// required number
return rev;
}
console.log(reverseBits(1000));
# 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))