In programming, you often need to convert decimal numbers into formats that computers interpret easily, such as binary, or formats used in memory dumps, such as hexadecimal.
Python provides convenient built-in functions to convert numbers into strings of these base notations.
This article explains the basic usage of bin(), oct(), and hex(), and how to remove the prefixes from the conversion results.
List of Conversion Functions
Here are the functions to convert numbers (integers) into strings for each base in Python.
| Function | Converted Base | Prefix |
| bin(x) | Binary | 0b |
| oct(x) | Octal | 0o |
| hex(x) | Hexadecimal | 0x |
These functions always return the result as a string (str type). Also, a prefix representing the base is automatically added to the beginning.
Specific Usage Examples
1. Converting to Binary: bin()
Converts an integer to a binary string.
# Convert decimal 255 to binary
val_bin = 255
result_bin = bin(val_bin)
print(f"Original: {val_bin}")
print(f"Converted: {result_bin}")
print(f"Type: {type(result_bin)}")
Execution Result:
Original: 255
Converted: 0b11111111
Type: <class 'str'>
2. Converting to Octal: oct()
Converts an integer to an octal string.
# Convert decimal 64 to octal
val_oct = 64
result_oct = oct(val_oct)
print(f"Original: {val_oct}")
print(f"Converted: {result_oct}")
Execution Result:
Original: 64
Converted: 0o100
3. Converting to Hexadecimal: hex()
Converts an integer to a hexadecimal string. This is often used for color codes and memory address representations.
# Convert decimal 65535 to hexadecimal
val_hex = 65535
result_hex = hex(val_hex)
print(f"Original: {val_hex}")
print(f"Converted: {result_hex}")
Execution Result:
Original: 65535
Converted: 0xffff
How to Convert Without Prefixes (0b, 0o, 0x)
bin(), oct(), and hex() are convenient, but they always add prefixes like 0b. If you do not need these, using the built-in function format() is a smart choice.
By passing format specifiers (b, o, x) as the second argument, you can get the string without the prefix.
number = 12345
# Binary
print(f"Binary: {format(number, 'b')}")
# Octal
print(f"Octal: {format(number, 'o')}")
# Hexadecimal - lowercase
print(f"Hexadecimal (lower): {format(number, 'x')}")
# Hexadecimal - uppercase
print(f"Hexadecimal (upper): {format(number, 'X')}")
Execution Result:
Plaintext
Binary: 11000000111001
Octal: 30071
Hexadecimal (lower): 3039
Hexadecimal (upper): 3039
Summary
- bin(int): Converts to binary string (
0b...). - oct(int): Converts to octal string (
0o...). - hex(int): Converts to hexadecimal string (
0x...). - If you do not need the prefix, use
format(int, 'b'), etc.
