How To Reverse A Binary Number In Python

Reversing a binary number is a common task in programming, especially in binary operations and bitwise manipulations. In this tutorial, we will learn how to reverse a binary number using Python.

This involves converting a decimal number to binary, reversing the binary digits, and converting the reversed binary number back to decimal.

Step 1: Convert Decimal to Binary

The first step in reversing a binary number is to convert a decimal number to its binary equivalent. Python has a built-in bin() function that can convert an integer to a binary string.
Here’s how to use the bin() function:

It is important to note that the bin() function returns a string with a ‘0b’ prefix, which denotes that the remaining characters are binary digits.

Step 2: Reverse the Binary Digits

Now that we have the binary representation of the number, we can reverse the binary digits by slicing the string from the third character and applying the [::-1] slicing operation:

Step 3: Convert Reversed Binary to Decimal

After reversing the binary digits, the final step is to convert the reversed binary number back to its decimal form using the int() function:

The int() function accepts two arguments: the first argument is the binary string, and the second argument is the base of the number system. Since binary is base 2, we pass 2 as the second argument to convert the binary string to an integer.

Putting It All Together

Here’s the complete code for reversing a binary number in Python:




In this tutorial, we learned how to reverse a binary number in Python using simple string manipulation and built-in functions. This approach is useful for various bitwise operations and binary manipulation tasks.