Converting numbers between different numeral systems is a common task in programming. One of the most fundamental conversions is from decimal (base-10) to binary (base-2). This is especially important in computer science, as binary numbers are the foundation of all digital systems.
- A decimal number is based on 10 and uses digits from 0 to 9. Examples: 25, 123, 10.
- A binary number is based on 2 and uses only two digits, 0 and 1. An example is 1010 (which is 10 in decimal).
This article will explore how to convert a decimal number to binary and vice versa using Python, covering multiple approaches, code examples, and explanations.
Table of contents
Convert Decimal to Binary
1. Using Python’s Built-in bin() Function
The bin() function in Python converts an integer number into its binary string representation.
Syntax: bin(x)
xmust be an integer (can be positive or negative).- Returns a string that starts with
'0b', followed by the binary representation of the integer. - For Example,
bin(5) = '0b101'
Use the below syntax if you want to remove the ‘0b’ prefix:
binary = bin(5)[2:] # Output: '101'
Note: [2:] slices a string from index 2 to the end, skipping the first two characters.
Code Example
decimal = 20
binary = bin(decimal)
print(f"Binary of {decimal} is {binary[2:]}")Code language: Python (python)
Output:
Binary of 20 is 10100
2. Using format() Function
The format() function in Python converts an integer decimal to its binary representation as a string, without the '0b' prefix.
Syntax: format(x, 'b')
must be an integer (can be positive or negative).x- Returns a string of binary representation of the integer.
- For Example,
format(5, 'b') = '101'
Note: No '0b' like with bin().
Code Example
decimal = 20
binary = format(decimal, 'b')
print(f"Binary of {decimal} is {binary}")
# Output:
# Binary of 20 is 10100Code language: Python (python)
3. Using F-String Formatting
An F-string (formatted string literal) lets you embed variables, expressions, or formatting instructions directly into a string using {}.
Just prefix the string with f or F and place variables or expressions inside {}.
For Example,
name = "Alice"
age = 25
f"My name is {name} and I am {age} years old." # Output: My name is Alice and I am 25 years old.Code language: Python (python)
Numbers can be formatted like this:
f"{3.14159:.2f}" # '3.14' → 2 decimal places
f"{255:x}" # 'ff' → hexadecimal of 255
f"{{5:b}}" # '101' → binary of 5
<strong>:b inside the f-string formats the decimal as binary</strong>Code language: Python (python)
Code Example
decimal = 20
print(f"Binary of {decimal} is {decimal:b}")
# Output:
# Binary of 20 is 10100Code language: Python (python)
4. Using While Loop
In this approach, we manually convert the decimal number into a binary number using while loop.
Algorithm to convert Decimal to Binary in Python:
- Divide the decimal number by 2
- Record the remainder
- Repeat the process with the quotient
- Reverse the remainders to get the binary value
For Example:
Convert 10 to binary
→ 10 ÷ 2 = 5 remainder 0
→ 5 ÷ 2 = 2 remainder 1
→ 2 ÷ 2 = 1 remainder 0
→ 1 ÷ 2 = 0 remainder 1
Binary = 1010
Code Example
decimal = 20
binary = ""
if decimal == 0:
binary = "0"
else:
while decimal > 0:
remainder = decimal % 2 # Get the remainder which is the last binary digit (0 or 1)
binary = str(remainder) + binary # Add it to the front of the result
decimal = decimal // 2 # Divide number by 2 (integer division)
print(binary)
# Output:
# 10100
Code language: Python (python)
5. Using Recursion
Recursion is a technique where a function calls itself to solve smaller parts of a problem until a base condition is met. It’s like solving a big problem by breaking it into smaller versions of the same problem.
In this approach, the algorithm used to convert decimals to binary is the same as explained in the above approach.
Step-by-step:
- It keeps dividing the number by 2, again and again.
- When it can’t divide anymore (when
nis 1 or 0), it stops. - As it comes back up (returns from each call), it prints the remainders (which are 1s and 0s).
- These remainders make up your binary number!
For Example: Convert 10 to Binary
10 // 2 = 5 → remainder = 0
5 // 2 = 2 → remainder = 1
2 // 2 = 1 → remainder = 0
1 is the stopping point → remainder = 1
Now we print the remainders from last to first: 1 → 0 → 1 → 0 → output = 1010
Function Calls Breakdown:
decimal_to_binary(10)- Calls
decimal_to_binary(10 // 2)i.e.decimal_to_binary(5) - Prints:
n % 2 = 10 % 2 = 0(after the recursive call)
- Calls
decimal_to_binary(5)- Calls
decimal_to_binary(2) - Prints:
5 % 2 = 1
- Calls
decimal_to_binary(2)- Calls
decimal_to_binary(1) - Prints:
2 % 2 = 0
- Calls
decimal_to_binary(1)- Does NOT call again (base case:
n <= 1) - Prints:
1 % 2 = 1
- Does NOT call again (base case:
Code Example
def decimal_to_binary(n):
if n > 1:
decimal_to_binary(n // 2)
print(n % 2, end='')
decimal = 20
print("Binary is: ", end='')
decimal_to_binary(decimal)
# Output:
# Binary is: 10100Code language: Python (python)
Convert Binary to Decimal
1. Using Built-in int() with Base 2
In this approach, we will be using the built-in function int() which converts a binary string to a decimal integer.
Syntax: int(x, base)
x: A string or number (in our case, a binary string, like"1010")base: The base of the number system (2for binary)- For Example:
int("1010", 2) # Output: 10
Code Example
binary = "1010"
decimal = int(binary, 2)
print(f"Decimal value of {binary} is {decimal}")
# Output:
# Decimal value of 1010 is 10Code language: Python (python)
2. Manual Conversion Using Loop
This approach does not use the built-in function but manually convert the Binary number into Decimal Number using for loop in Python.
How it works:
Binary is base-2, meaning each digit represents a power of 2, from right to left. It parses the string "1010" as a binary number, as follows:
( 1 × 2³ ) + ( 0 × 2² ) + ( 1 × 2¹ ) + ( 0 × 2⁰ )
= 8 + 0 + 2 + 0
= 10
Code Example
binary = "1010"
decimal = 0
power = 0
for digit in reversed(binary):
decimal += int(digit) * (2 ** power)
power += 1
print(f"Decimal value is {decimal}")
# Output:
# Decimal value is 10Code language: Python (python)
Explanation
- Start with two variables:
decimal = 0→ This will store the final decimal result.power = 0→ Keeps track of the power of 2 (starts from rightmost digit).
reversed(binary): We reverse the binary string so we can process it from right to left, starting from the least significant bit (LSB) — the one at the end.- For each digit in the reversed binary string:
- Convert the digit from string to integer:
int(digit) - Multiply the digit by
2 ** power(power of 2) - Add the result to the
decimalvariable - Increase
powerby 1 (to move to the next binary digit’s place value)
- Convert the digit from string to integer:
- After the loop ends, the
decimalvariable holds the final decimal value. - Print or return the decimal result.
Let’s walk through the loop for "1010":
Initial values:
decimal = 0power = 0
Loop iterations:
- First digit (LBS): ‘0’
→decimal += 0 * 2^0 = 0
→power = 1 - Second digit: ‘1’
→decimal += 1 * 2^1 = 2
→power = 2 - Third digit: ‘0’
→decimal += 0 * 2^2 = 0
→power = 3 - Fourth digit: ‘1’
→decimal += 1 * 2^3 = 8
→power = 4
Final result: decimal = 0 + 2 + 0 + 8 = 10
Summary
Python offers multiple ways to convert a decimal number to binary and vice versa. You can use built-in functions like bin(), int(), format(), and f-strings for quick solutions, or write manual or recursive methods to understand the logic deeply.

Leave a Reply