Python Tutorial (33) - Example: Convert decimal to binary, octal, and hexadecimal

Time: Column:Python views:216

Converting Decimal Numbers to Binary, Octal, and Hexadecimal

The following code demonstrates how to convert decimal numbers to binary, octal, and hexadecimal formats:

Example

# Get user input for a decimal number
dec = int(input("Enter a number: "))

print("Decimal number:", dec)
print("Converted to binary:", bin(dec))
print("Converted to octal:", oct(dec))
print("Converted to hexadecimal:", hex(dec))

Example Output:

$ python3 test.py 
Enter a number: 5
Decimal number: 5
Converted to binary: 0b101
Converted to octal: 0o5
Converted to hexadecimal: 0x5

The following examples demonstrate how to convert between different numeral systems. You can adjust the input and output bases as needed.

Binary to Other Bases

# Convert binary to decimal, octal, and hexadecimal
binary_number = '101010'
decimal_number = int(binary_number, 2)  # Binary to decimal
octal_number = oct(decimal_number)      # Decimal to octal
hexadecimal_number = hex(decimal_number)  # Decimal to hexadecimal

print('Binary number:', binary_number)
print('Converted to decimal:', decimal_number)
print('Converted to octal:', octal_number)
print('Converted to hexadecimal:', hexadecimal_number)

Example Output:

Binary number: 101010
Converted to decimal: 42
Converted to octal: 0o52
Converted to hexadecimal: 0x2a

Octal to Other Bases

# Convert octal to decimal, binary, and hexadecimal
octal_number = '52'
decimal_number = int(octal_number, 8)      # Octal to decimal
binary_number = bin(decimal_number)         # Decimal to binary
hexadecimal_number = hex(decimal_number)    # Decimal to hexadecimal

print('Octal number:', octal_number)
print('Converted to decimal:', decimal_number)
print('Converted to binary:', binary_number)
print('Converted to hexadecimal:', hexadecimal_number)

Example Output:

Octal number: 52
Converted to decimal: 42
Converted to binary: 0b101010
Converted to hexadecimal: 0x2a

Hexadecimal to Other Bases

# Convert hexadecimal to decimal, binary, and octal
hexadecimal_number = '2a'
decimal_number = int(hexadecimal_number, 16)   # Hexadecimal to decimal
binary_number = bin(decimal_number)             # Decimal to binary
octal_number = oct(decimal_number)              # Decimal to octal

print('Hexadecimal number:', hexadecimal_number)
print('Converted to decimal:', decimal_number)
print('Converted to binary:', binary_number)
print('Converted to octal:', octal_number)

Example Output:

Hexadecimal number: 2a
Converted to decimal: 42
Converted to binary: 0b101010
Converted to octal: 0o52