Convert Binary to Decimal in Python
What you’ll learn
- How binary place values (
1,2,4,8...) create a decimal number. - How to convert using a manual loop and Python built-in
int(s, 2). - How to validate input and explain complexity in interviews.
Overview
Binary uses base 2. Each bit contributes a power of two. Decimal uses base 10. Binary-to-decimal conversion adds contributions from all bit positions.
Quick examples
101010
1117
10000032
Live preview
Enter a binary string (0 and 1 only) and convert it to decimal.
Algorithm (manual method)
Start from the rightmost bit
Set position to 0 and total to 0.
For each bit
If bit is 1, add 2^position to total.
Move left
Increase position by 1 and continue.
📜 Pseudocode
Pseudocode
function binary_to_decimal(s):
if s has characters other than 0 and 1:
return error
total = 0
power = 0
for bit from right to left in s:
if bit == '1':
total = total + (2 ^ power)
power = power + 1
return total 1
Manual conversion using powers of 2
python
def binary_to_decimal_manual(bits: str) -> int:
bits = bits.strip()
if not bits or any(ch not in "01" for ch in bits):
raise ValueError("Binary string must contain only 0 and 1")
total = 0
power = 0
for ch in reversed(bits):
if ch == "1":
total += 2 ** power
power += 1
return total
binary_number = "101010"
decimal_number = binary_to_decimal_manual(binary_number)
print(f"Binary: {binary_number}")
print(f"Decimal: {decimal_number}") 2
Using Python built-in int(..., 2)
python
def binary_to_decimal_builtin(bits: str) -> int:
bits = bits.strip()
if not bits or any(ch not in "01" for ch in bits):
raise ValueError("Binary string must contain only 0 and 1")
return int(bits, 2)
binary_number = "101010"
print(f"Binary: {binary_number}")
print(f"Decimal: {binary_to_decimal_builtin(binary_number)}") ❓ FAQ
You can use int(binary_string, 2), or convert manually by adding powers of 2 for each bit position.
Binary numbers can only contain 0 and 1. Validation prevents wrong answers and runtime errors.
It parses the string s as a base-2 number and returns its decimal integer value.
O(k), where k is the number of bits.
No for normal integer conversion. Python integers can grow very large, limited by memory.
Yes. Values like 00101 are valid and equal to 5 in decimal.
Edge cases and pitfalls
Invalid chars
Contains 2 or letters
Reject strings like 1021 or 10a1.
Empty input
No bits provided
Return a clear error instead of converting.
Leading zeros
Allowed
00101 is still valid and equals 5.
⏱️ Time and space complexity
| Approach | Time | Extra space |
|---|---|---|
| Manual loop over bits | O(k) | O(1) |
Built-in int(bits, 2) | O(k) | O(1) |
Summary
- Math: add powers of two for 1 bits.
- Code: manual method or
int(bits, 2). - Safety: validate that input has only 0 and 1.
Did you know?
Binary 101010 means 32 + 8 + 2, so its decimal value is 42.
9 people found this page helpful
