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
Selected Reading
How to Convert Decimal to Binary, Octal, and Hexadecimal using Python?
Python provides built-in functions to convert decimal numbers to different number systems. These functions are bin() for binary, oct() for octal, and hex() for hexadecimal conversion.
Syntax
bin(number) # Returns binary representation oct(number) # Returns octal representation hex(number) # Returns hexadecimal representation
Basic Conversion Example
Here's how to convert a decimal number to different number systems ?
decimal = 27 print(bin(decimal), "in binary.") print(oct(decimal), "in octal.") print(hex(decimal), "in hexadecimal.")
0b11011 in binary. 0o33 in octal. 0x1b in hexadecimal.
Removing Prefixes
The built-in functions include prefixes (0b, 0o, 0x). To get clean output without prefixes ?
decimal = 42
binary = bin(decimal)[2:] # Remove '0b' prefix
octal = oct(decimal)[2:] # Remove '0o' prefix
hexadecimal = hex(decimal)[2:] # Remove '0x' prefix
print(f"Binary: {binary}")
print(f"Octal: {octal}")
print(f"Hexadecimal: {hexadecimal}")
Binary: 101010 Octal: 52 Hexadecimal: 2a
Converting Multiple Numbers
You can convert multiple decimal numbers using a loop ?
numbers = [8, 16, 32, 64]
print("Decimal\tBinary\tOctal\tHex")
print("-" * 35)
for num in numbers:
binary = bin(num)[2:]
octal = oct(num)[2:]
hexadecimal = hex(num)[2:]
print(f"{num}\t{binary}\t{octal}\t{hexadecimal}")
Decimal Binary Octal Hex ----------------------------------- 8 1000 10 8 16 10000 20 10 32 100000 40 20 64 1000000 100 40
Key Points
-
bin()returns binary with '0b' prefix -
oct()returns octal with '0o' prefix -
hex()returns hexadecimal with '0x' prefix - Use slicing
[2:]to remove prefixes - All functions accept positive integers
Conclusion
Python's bin(), oct(), and hex() functions provide easy decimal conversion to different number systems. Use slicing to remove prefixes when needed for clean output formatting.
Advertisements
