Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python Decimal to Binary, Octal, and Hexadecimal Conversion

Python Decimal to Binary, Octal, and Hexadecimal Conversion

Document Object Reference Manual Python3 Examples

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:

"

)

)

print

(

"

The decimal number is:

"

,

dec

)

print

(

"

Converted to binary:

"

,

bin

(

dec

)

)

print

(

"

Converted to octal:

"

,

oct

(

dec

)

)

print

(

"

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

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 Object Reference Manual Python3 Examples