Python: How to Convert Any Number to Another Base (Binary, Octal, Hexadecimal)
| Python | Programming |

In this tutorial, you will learn how to convert numbers between different bases in Python, including binary, octal, and hexadecimal. You will learn how to use Python's built-in functions, as well as techniques to create your own custom conversions.
By the end, you will be able to convert any number to the base you need and handle numerical representations efficiently in your programs.
Converting Numbers to Binary, Octal, and Hexadecimal
Python includes built-in functions to convert integers to different bases:
number = 42
# Binary
binary = bin(number)
print(binary) # Output: 0b101010
# Octal
octal = oct(number)
print(octal) # Output: 0o52
# Hexadecimal
hexadecimal = hex(number)
print(hexadecimal) # Output: 0x2a
The functions
bin(),oct(), andhex()return strings with prefixes that indicate the base (0b,0o,0x).
Converting to Any Custom Base
If you want to convert a number to any base between 2 and 36, you can use a custom function:
def convert_base(number, base):
digits = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
if number < base:
return digits[number]
else:
return convert_base(number // base, base) + digits[number % base]
# Example
print(convert_base(255, 2)) # 11111111
print(convert_base(255, 16)) # FF
print(convert_base(255, 8)) # 377
This function allows you to represent a number in any base up to 36, using digits and letters.
Converting From Another Base to Decimal
To convert numbers from any base to decimal, you can use Python's int() function:
# From binary to decimal
print(int("1010", 2)) # 10
# From octal to decimal
print(int("52", 8)) # 42
# From hexadecimal to decimal
print(int("2A", 16)) # 42
The
int(string, base)function interprets the string according to the specified base and returns a decimal number.
With these tools, you can:
- Convert integers from decimal to binary, octal, or hexadecimal.
- Convert numbers to any custom base using recursion.
- Convert numbers from any base to decimal for calculations and processing.
These techniques are useful for low-level programming, cryptography, data processing, and tasks where numerical representation matters.