Python Decimal to Binary, Octal, and Hexadecimal Conversion
The following code converts decimal to binary, octal, and hexadecimal:
Example (Python 3.0+)
-- coding: UTF-8 --
Filename : test.py
author by : www.runoob.com
Get a decimal number from the user
dec
=
int
(
input
(
"
Enter a number:
"
)
)
(
"
The decimal number is:
"
,
dec
)
(
"
Converted to binary:
"
,
bin
(
dec
)
)
(
"
Converted to octal:
"
,
oct
(
dec
)
)
(
"
Converted to hexadecimal:
"
,
hex
(
dec
)
)
The output of the code above is:
python3 test.py
输入数字:5
十进制数为:5
转换为二进制为: 0b101
转换为八进制为: 0o5
转换为十六进制为: 0x5
The following example shows how to convert between different bases; you can change the input base value and output base form 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
(
'Binary number:'
,
binary_number
)
(
'Converted to decimal:'
,
decimal_number
)
(
'Converted to octal:'
,
octal_number
)
(
'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
(
'Octal number:'
,
octal_number
)
(
'Converted to decimal:'
,
decimal_number
)
(
'Converted to binary:'
,
binary_number
)
(
'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
(
'Hexadecimal number:'
,
hexadecimal_number
)
(
'Converted to decimal:'
,
decimal_number
)
(
'Converted to binary:'
,
binary_number
)
(
'Converted to octal:'
,
octal_number
)
Output result:
十六进制数: 2a
转换为十进制: 42
转换为二进制: 0b101010
转换为八进制: 0o52
Python3 Examples