When handling numbers in Python programs, we usually use decimal numbers (0-9). However, depending on the application, it may be more intuitive to use binary, octal, or hexadecimal.
For example, binary is suitable for bitwise operations, octal for setting file permissions, and hexadecimal for specifying color information or processing binary data.
In Python, you can write these N-base numbers directly by adding a specific prefix to the beginning of the number.
This article explains the notation methods for each base and how to handle them in Python.
List of Prefixes for N-Base Notation
The main integer literal notations available in Python are as follows. Case is not distinguished, but lowercase (e.g., 0x) is generally used for readability.
| Prefix | Base | Meaning | Allowed Characters |
| 0b or 0B | Binary | Base-2 number | 0, 1 |
| 0o or 0O | Octal | Base-8 number | 0 – 7 |
| 0x or 0X | Hexadecimal | Base-16 number | 0 – 9, a – f (A – F) |
Usage Examples for Each Base
When you assign values using these notations, Python treats them internally as normal “integers (int)”. Therefore, when you output them using functions like print(), they are converted to decimal by default.
1. Binary (0b)
Often used for managing bit flags.
# Defined in binary (Decimal 10)
binary_val = 0b1010
print(f"Value: {binary_val}")
print(f"Type: {type(binary_val)}")
Execution Result:
Value: 10
Type: <class 'int'>
2. Octal (0o)
Seen in permission settings for file systems like Linux.
# Defined in octal (Equivalent to file permission 755)
# 7*64 + 5*8 + 5*1 = 493
octal_val = 0o755
print(f"Value: {octal_val}")
Execution Result:
Value: 493
3. Hexadecimal (0x)
Used in a wide range of fields, such as memory addresses, color codes, and character codes.
# Defined in hexadecimal (Assuming RGB color red, etc.)
# FF(255) * 65536 + 00 * 256 + 00
hex_val = 0xFF0000
print(f"Value: {hex_val}")
Execution Result:
Value: 16711680
Converting Decimal to N-Base Strings
Conversely, if you want to convert a decimal number into a “binary string” or similar to check it, use the following built-in functions:
bin(x): Convert to binary stringoct(x): Convert to octal stringhex(x): Convert to hexadecimal string
number = 255
print(f"Binary: {bin(number)}")
print(f"Octal: {oct(number)}")
print(f"Hexadecimal: {hex(number)}")
Execution Result:
Binary: 0b11111111
Octal: 0o377
Hexadecimal: 0xff
Summary
In Python, you can write N-base numbers directly in your code by adding prefixes.
- 0b: Binary
- 0o: Octal
- 0x: Hexadecimal
Internally, they are all handled as integer int types, and you can use them for calculations and output without distinction.
