Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Quickly convert Decimal to other bases in Python
To quickly convert decimal numbers to other bases, Python provides built-in functions that make the process simple and efficient ?
- Decimal to Binary ? bin()
- Decimal to Octal ? oct()
- Decimal to Hexadecimal ? hex()
The decimal number system has base 10 and uses digits 0-9. Binary (base 2) uses only 0 and 1. Octal (base 8) uses digits 0-7. Hexadecimal (base 16) uses digits 0-9 and letters A-F (where A=10, B=11, C=12, D=13, E=14, F=15).
Convert Decimal to Binary
The bin() function converts a decimal number to its binary representation ?
# Decimal Number
dec = 110
# Display the Decimal Number
print("Decimal = ", dec)
# Display the Binary form
print('The number {} in binary form = {}'.format(dec, bin(dec)))
Decimal = 110 The number 110 in binary form = 0b1101110
Convert Decimal to Octal
The oct() function converts a decimal number to its octal representation ?
# Decimal Number
dec = 110
# Display the Decimal Number
print("Decimal = ", dec)
# Display the Octal form
print('The number {} in octal form = {}'.format(dec, oct(dec)))
Decimal = 110 The number 110 in octal form = 0o156
Convert Decimal to Hexadecimal
The hex() function converts a decimal number to its hexadecimal representation ?
# Decimal Number
dec = 110
# Display the Decimal Number
print("Decimal = ", dec)
# Display the Hexadecimal form
print('The number {} in hexadecimal form = {}'.format(dec, hex(dec)))
Decimal = 110 The number 110 in hexadecimal form = 0x6e
Converting Multiple Numbers at Once
You can also convert multiple decimal numbers efficiently using a loop ?
numbers = [10, 25, 100, 255]
for num in numbers:
print(f"Decimal: {num}")
print(f"Binary: {bin(num)}")
print(f"Octal: {oct(num)}")
print(f"Hexadecimal: {hex(num)}")
print("-" * 20)
Decimal: 10 Binary: 0b1010 Octal: 0o12 Hexadecimal: 0xa -------------------- Decimal: 25 Binary: 0b11001 Octal: 0o31 Hexadecimal: 0x19 -------------------- Decimal: 100 Binary: 0b1100100 Octal: 0o144 Hexadecimal: 0x64 -------------------- Decimal: 255 Binary: 0b11111111 Octal: 0o377 Hexadecimal: 0xff --------------------
Removing Prefixes
If you want the converted numbers without prefixes (0b, 0o, 0x), use slicing ?
dec = 110
print(f"Binary without prefix: {bin(dec)[2:]}")
print(f"Octal without prefix: {oct(dec)[2:]}")
print(f"Hexadecimal without prefix: {hex(dec)[2:]}")
Binary without prefix: 1101110 Octal without prefix: 156 Hexadecimal without prefix: 6e
Conclusion
Python's built-in functions bin(), oct(), and hex() provide quick and easy decimal to base conversion. Use slicing to remove prefixes when needed for cleaner output.
