- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- 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?
First convert number into binary using bin() function. Then skip the first two character of binary representation because bin() appends 0b as a prefix in a binary representation of the number and reverse the remaining part. From also character and reverse it till second last character from left. Convert a reversed binary string into integer.
Algorithm
integernumber(n,bit_size) /* n is the number and bit_size is the bitsize */ Step 1: first convert number into binary . Step 2: skip the first two characters of binary representation string and reverse. Step 3: remaining string and then append 0’s after it. Step 4: from the last character and reverse it until second last character from the left. Step 5: converts reversed binary string into an integer.
Example Code
# Python Program reverse bits of positive integer number defintegernumber(n,bit_size): bin_number = bin(n) reverse_number = bin_number[-1:1:-1] reverse_number = reverse_number + (bit_size - len(reverse_number))*'0' print ("Reverse Bits ::>",int(reverse_number,2)) # Driver program if __name__ == "__main__": n = int(input("Enter Number ::>")) bit_size = int(input("Enter Bit Size ::>")) integernumber(n,bit_size)
output
Enter Number ::>1 Enter Bit Size ::>32 Reverse Bits ::> 2147483648 Enter Number ::>2147483648 Enter Bit Size ::>32 Reverse Bits ::> 1
Advertisements