Reverse bits of a positive integer number in Python
Last Updated :
10 Apr, 2023
Given an positive integer and size of bits, reverse all bits of it and return the number with reversed bits.Examples:
Input : n = 1, bitSize=32
Output : 2147483648
On a machine with size of
bit as 32. Reverse of 0....001 is
100....0.
Input : n = 2147483648, bitSize=32
Output : 1
We can solve this problem quickly in Python. Approach is very simple,
- Convert integer number into it's binary representation using bin(num) function.
- bin() function appends 0b as a prefix in binary representation of number, skip first two characters of binary representation and reverse remaining part of string.
- As we know in memory any binary representation of a number is filled with leading zeros after last set bit from left that means we need to append bitSize - len(reversedBits) number of zeros after reversing remaining string.
- Now convert binary representation into integer number using int(string,base) method.
How int() method works ?
int(string,base) method takes a string and base to identify that string is referring to what number system ( binary=2, hexadecimal=16, octal=8 etc. ) and converts string into decimal number system accordingly. For example ; int('1010',2) = 10.
Python3
# Function to reverse bits of positive
# integer number
def reverseBits(num,bitSize):
# Convert number into binary representation
# output will be like bin(10) = '0b10101'
binary = bin(num)
# Skip first two characters of binary
# representation string and reverse
# remaining string and then append zeros
# after it. binary[-1:1:-1] --> start
# from last character and reverse it until
# second last character from left
reverse = binary[-1:1:-1]
reverse = reverse + (bitSize - len(reverse))*'0'
# converts reversed binary string into integer
print (int(reverse,2))
# Driver program
if __name__ == '__main__':
num = 1
bitSize = 32
reverseBits(num, bitSize)
Another way to revert bits without converting to string:
This is based on the concept that if the number (say N) is reversed for X bit then the reversed number will have the value same as:
the maximum possible number of X bits - N
= 2X - 1 - N
Follow the steps to implement this idea:
- Find the highest number that can be formed by the given number.
- Subtract the given number from that.
- Return the numbers.
Below is the implementation of the given approach.
Python3
# 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
# choose a binary size which we want to reverse
size = 32
print(reverse_bits(num, size))
Approach#3: Using bit manipulation
This approach reverses the bits of a given positive integer number n with the given bit size bitSize. It iterates through all the bits of n using a for loop and checks if the i-th bit is set to 1 by performing a bitwise AND operation between n and a left-shifted 1 by i. If it's set, it sets the corresponding bit in the result variable using a bitwise OR operation between result and a left-shifted 1 by bitSize - 1 - i. Finally, it returns the result.
Algorithm
1. Initialize result to 0.
2. Iterate through each bit position from 0 to 31:
a. If the bit in the input number is set, set the corresponding bit in the result to 1 shifted by 31 minus the bit position.
3. Return the result.
Python3
def reverse_bits(n, bitSize):
result = 0
for i in range(bitSize):
if n & (1 << i):
result |= 1 << (bitSize - 1 - i)
return result
n=2147483648
bitSize=32
print(reverse_bits(n, bitSize))
Time Complexity: O(1), since we always iterate through 32 bits.
Space Complexity: O(1), since we only use a constant amount of memory for variables.
Similar Reads
What is the maximum possible value of an integer in Python ?
Consider below Python program. Python3 # A Python program to demonstrate that we can store # large numbers in Python x = 10000000000000000000000000000000000000000000 x = x + 1 print (x) Output : 10000000000000000000000000000000000000000001 In Python, value of an integer is not restricted by the numb
2 min read
Reverse digits of an integer with overflow handled
Write a program to reverse an integer assuming that the input is a 32-bit integer. If the reversed integer overflows, print -1 as the output. Let us see a simple approach to reverse digits of an integer. C++// A simple C program to reverse digits of // an integer. #include <bits/stdc++.h> usin
15 min read
Find Average of a Number Digits in Python
AIn this article, we will see how to find the average of the digits of a number in Python. Examples: Input: N = 642 Output: 4.0 Explanation: (6+4+2)/3 = 12/3 = 4.0 Input: N = 3504 Output: 3.0 Explanation: (3+5+0+4)/4 = 12/4 = 3.0Calculate the average of a number of digits in python if the number is
3 min read
Reverse actual bits of the given number
Given a non-negative integer n, the task is to reverse the bits in its binary representation and return the resulting decimal number. The reversal should consider only the actual binary digits without any leading zeros.Examples : Input : 11Output : 13Explanation: (11)10 = (1011)2.After reversing the
4 min read
Write an Efficient C Program to Reverse Bits of a Number
Given an unsigned integer, reverse all bits of it and return the number with reversed bits. Input : n = 1Output : 2147483648 Explanation : On a machine with size of unsigned bit as 32. Reverse of 0....001 is 100....0. Input : n = 2147483648Output : 1 Recommended PracticeReverse BitsTry It!Method1 -
6 min read
Reverse digits of an integer with overflow handled | Set 2
Given a 32-bit integer N. The task is to reverse N, if the reversed integer overflows, print -1 as the output. Examples Input: N = 123Output: 321 Input: N = -123Output: -321 Input: N = 120Output: 21 Approach: Unlike approaches Set 1 of the article, this problem can be solved simply by using a 64-bit
9 min read
Python Bin | Count total bits in a number
Given a positive number n, count total bit in it. Examples: Input : 13 Output : 4 Binary representation of 13 is 1101 Input : 183 Output : 8 Input : 4096 Output : 13 We have existing solution for this problem please refer Count total bits in a number link. Approach#1: We can solve this problem quick
3 min read
Python | Reverse a numpy array
As we know Numpy is a general-purpose array-processing package that provides a high-performance multidimensional array object, and tools for working with these arrays. Let's discuss how can we reverse a Numpy array. Using flip() function to Reverse a Numpy array The numpy.flip() function reverses t
2 min read
Reversing a List in Python
In this article, we are going to explore multiple ways to reverse a list. Python provides several methods to reverse a list using built-in functions and manual approaches. The simplest way to reverse a list is by using the reverse() method. Let's take an example to reverse a list using reverse() met
4 min read
Emulating Numeric types in Python
The following are the functions which can be defined to emulate numeric type objects. Methods to implement Binary operations on same type of objects : These functions will make no change in the calling object rather they will return a new numeric object of same type after performing certain operatio
3 min read