Python program to reverse bits of a positive integer number?

In Python, every number is represented internally as a sequence of binary digits, known as bits. In this article, we are going to learn how to reverse the bits of a positive integer number using different approaches.

What is Bit Reversal?

When we reverse bits of an integer value, we flip the order of its binary digits such that the least significant bit becomes the most significant bit and vice versa.

Bit Reversal Example Original: 10 1 0 1 0 Reversed: 0 1 0 1

Using bin() and Slice Operator

The bin() function converts an integer to its binary representation, and the slice operator [::-1] reverses the string ?

Syntax

bin(number)[2:][::-1]

Where [2:] removes the '0b' prefix and [::-1] reverses the binary string.

Example 1: Reversing Bits of 5

def reverse_bits_string(n):
    binary_repr = bin(n)[2:]
    print(f"Original number: {n}")
    print(f"Binary representation: {binary_repr}")
    reversed_bits = binary_repr[::-1]
    print(f"Reversed bits: {reversed_bits}")
    return int(reversed_bits, 2)

result = reverse_bits_string(5)
print(f"Reversed number: {result}")
Original number: 5
Binary representation: 101
Reversed bits: 101
Reversed number: 5

Example 2: Reversing Bits of 10

def reverse_bits_string(n):
    binary_repr = bin(n)[2:]
    print(f"Original number: {n}")
    print(f"Binary representation: {binary_repr}")
    reversed_bits = binary_repr[::-1]
    print(f"Reversed bits: {reversed_bits}")
    return int(reversed_bits, 2)

result = reverse_bits_string(10)
print(f"Reversed number: {result}")
Original number: 10
Binary representation: 1010
Reversed bits: 0101
Reversed number: 5

Using Bit Manipulation

We can also reverse bits using bitwise operations for better performance ?

def reverse_bits_bitwise(n):
    result = 0
    original = n
    
    while n:
        result = (result << 1) | (n & 1)
        n >>= 1
    
    print(f"Original number: {original}")
    print(f"Reversed bits result: {result}")
    return result

# Test with different numbers
reverse_bits_bitwise(10)
print()
reverse_bits_bitwise(12)
Original number: 10
Reversed bits result: 5

Original number: 12
Reversed bits result: 3

Comparison

Method Approach Performance Best For
String Slicing Convert to binary string, reverse Slower Easy to understand
Bit Manipulation Use bitwise operations Faster Performance-critical code

Conclusion

Use string slicing with bin() for simple bit reversal operations. For performance-critical applications, bitwise manipulation provides a faster solution. Both methods effectively reverse the binary representation of positive integers.

Updated on: 2026-03-24T20:59:56+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements