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.

Reversing the bits of a Positive Integer Number

If we reverse bits of an integer value, we are flipping the order of its binary digits such that the least important bit becomes the most important and vice versa. 

The Python bin() Function: The Python bin() function accepts an integer value and converts the given integer to its binary representation. Following is the syntax of this function -

bin(i)

Slice Operator in Python: The Python slice operator is used to retrieve one or more elements of a sequence. We can retrieve a portion of a sequence by specifying the desired range of elements. Following is the syntax of the slice operator -

sequence[start:end:step]

Where,

  • start is the beginning of the range.
  • stop is the end of the range.
  • step is the increment value for each element.

If we do not provide the start and stop values, this operator will return the list as it is, and if we pass "-1" as the step value, this operator reverses the contents of the sequence and returns it. To reverse the bits of a positive integer -

  • Retrieve its binary representation using the bin() function. Skip the first two characters.
  • Reverse its contents using the slice operator.

Example 1

Let's look at the following example, where we are going to consider the integer as '5' and observe the output.

def demo(n):
   x = bin(n)[2:] 
   print("Original binary_representation:", x)
   result = x[::-1]
   print("Reversed binary_representation:", result)
demo(5)

The output of the above program is as follows -

Original binary_representation: 101
Reversed binary_representation: 101

Example 2

Consider another scenario, where we are going to use the integer '10' and observe the output.

def demo(n):
   x = bin(n)[2:] 
   print("Original binary_representation:", x)
   result = x[::-1]
   print("Reversed binary_representation:", result)
demo(10)

The output of the above program is as follows -

Original binary_representation: 1010
Reversed binary_representation: 0101
Updated on: 2025-06-19T18:23:53+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements