🕯️ Magic Note
Binary is base 2. Each digit represents a power of two. The rightmost digit is 2⁰ (1), the next is 2¹ (2), then 2² (4), and so on. The string “101” means (1 × 4) + (0 × 2) + (1 × 1) = 5. int(‘101’, 2) performs this calculation and returns 5. The same function works for any base from 2 to 36.
- The base parameter can be any integer from 2 to 36
- Binary strings must contain only 0 and 1 characters
- Case insensitive for bases above 10, ‘A’ and ‘a’ both mean 10
- Raises ValueError if the string contains invalid digits for the base
| Call | Base | Result |
|---|---|---|
| int(‘101’, 2) | Binary (base 2) | 5 |
| int(’12’, 8) | Octal (base 8) | 10 |
| int(‘A’, 16) | Hexadecimal (base 16) | 10 |
| int(‘1111’, 2) | Binary | 15 |
| int(‘FF’, 16) | Hexadecimal | 255 |
| int(‘101’, 3) | Ternary (base 3) | 10 |
Python
# Converting binary string to integer
binary_string = “101”
number = int(binary_string, 2)
print(number)
# Output: 5
print(type(number))
# Output:
Python
# Working with different bases
binary = int(“1101”, 2)
octal = int(“17”, 8)
hexadecimal = int(“1A3F”, 16)
ternary = int(“210”, 3)
print(f”Binary 1101 = {binary}”)
print(f”Octal 17 = {octal}”)
print(f”Hex 1A3F = {hexadecimal}”)
print(f”Ternary 210 = {ternary}”)
# Output: Binary 1101 = 13
# Output: Octal 17 = 15
# Output: Hex 1A3F = 6719
# Output: Ternary 210 = 21
Python
# Converting back to binary string
number = 42
binary = bin(number)
octal = oct(number)
hexadecimal = hex(number)
print(f”42 in binary: {binary}”)
print(f”42 in octal: {octal}”)
print(f”42 in hexadecimal: {hexadecimal}”)
# Output: 42 in binary: 0b101010
# Output: 42 in octal: 0o52
# Output: 42 in hexadecimal: 0x2a
- Forgetting the base argument, writing int(‘101’) which returns 101, not 5
- Using invalid digits for the base, like int(‘102’, 2) (2 is not valid in binary)
- Passing a binary literal like int(0b101) which already gives 5, making the base unnecessary
⚡ Whisper
The pattern hides beneath the surface. Ones and zeros arranged in sacred order. Python leans close and listens. The meaning emerges. A whisper becomes a number. Order becomes value. The binary speaks, and Python understands.