Python Decimal to Binary, Octal, Hexadecimal

Document 对象参考手册Python3 Examples

The following code is used to convert decimal to binary, octal, and hexadecimal:

Example (Python 3.0+)

# -*- coding: UTF-8 -*- # Filename : test.py # author by : www.example.com # Get user input 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))

Executing the above code produces the following output:

python3 test.py 
输入数字:5
十进制数为:5
转换为二进制为: 0b101
转换为八进制为: 0o5
转换为十六进制为: 0x5

The following examples show how to convert between different bases. You can modify the input base value and the output base format as needed.

Binary Conversion Example

Example

binary_number = '101010'
decimal_number = int(binary_number, 2)  # Convert binary to decimal
octal_number = oct(decimal_number)      # Convert decimal to octal
hexadecimal_number = hex(decimal_number)  # Convert 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)

Output result:

二进制数: 101010
转换为十进制: 42
转换为八进制: 0o52
转换为十六进制: 0x2a

Octal Conversion Example

Example

octal_number = '52'
decimal_number = int(octal_number, 8)      # Convert octal to decimal
binary_number = bin(decimal_number)         # Convert decimal to binary
hexadecimal_number = hex(decimal_number)    # Convert 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)

Output result:

八进制数: 52
转换为十进制: 42
转换为二进制: 0b101010
转换为十六进制: 0x2a

Hexadecimal Conversion Example

Example

hexadecimal_number = '2a'
decimal_number = int(hexadecimal_number, 16)   # Convert hexadecimal to decimal
binary_number = bin(decimal_number)             # Convert decimal to binary
octal_number = oct(decimal_number)              # Convert 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)

Output result:

十六进制数: 2a
转换为十进制: 42
转换为二进制: 0b101010
转换为八进制: 0o52

Document 对象参考手册Python3 Examples

Other Extensions