Python Program to Convert Decimal to Binary, Octal, and Hexadecimal Formats

In this example, you will learn to convert decimal numbers to binary, octal, and hexadecimal number formats.

If a number is prefixed with 0b, it is regarded as binary, while 0o signifies that it is octal, and 0x indicates that it is in hexadecimal format.

Here are some examples of decimal, binary, octal, and hexadecimal numbers:

Decimal: 42, 123, 1000, 65535
Binary: 0b101010, 0b1111011, 0b1111101000, 0b1111111111111111
Octal: 0o52, 0o173, 0o1750, 0o177777
Hexadecimal: 0x2A, 0x7B, 0x3E8, 0xFFFF

Python Program to Convert Decimal to Binary number format

# Define a decimal number
decimal_num = 178

# Convert decimal to binary using the bin() function
binary_num = bin(decimal_num)

# Print the binary number
print(binary_num)


Output

0b10110010

Real-world use case:

In computer programming, binary numbers are used to represent machine instructions.

Converting decimal numbers to binary is useful when working with low-level programming languages and computer systems that use binary data formats in fact computer all digital systems use binary format to represent data and information.

Program to Convert Decimal to Octal

Octal numbers are often used in computer programming to represent file permissions or hardware addresses.

Converting decimal numbers to octal is useful when working with Unix-based operating systems or programming languages that use octal notation.

# Define a decimal number
decimal_num = 178

# Convert decimal to octal using the oct() function
octal_num = oct(decimal_num)

# Print the octal number
print(octal_num)

Output

0o262

Convert Decimal to Hexadecimal

Hexadecimal numbers are used in computer programming to represent memory addresses or color values.

Converting decimal numbers to hexadecimal is useful when working with graphics programming, web development, and low-level system programming.

Use hex built-in function to convert to decimal to hexadecimal

# Define a decimal number
decimal_num = 178

# Convert decimal to hexadecimal using the hex() function
hexadecimal_num = hex(decimal_num)

# Print the hexadecimal number
print(hexadecimal_num)

Output

0xb2

In summary, you can bin, oct, and hex function to convert decimals to their respective format as shown below in the example


# Define a decimal number
dec = 1023

# Convert decimal to binary using the bin() function
binary = bin(dec)

# Convert decimal to octal using the oct() function
octal = oct(dec)

# Convert decimal to hexadecimal using the hex() function
hexadecimal = hex(dec)

# Print the results
print("The decimal value of", dec, "is:")
print(binary, "in binary.")
print(octal, "in octal.")
print(hexadecimal, "in hexadecimal.")

Output

The decimal value of 1023 is:
0b1111111111 in binary.
0o1777 in octal.
0x3ff in hexadecimal.

Leave a Comment