
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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