Home > Backend Development > Python Tutorial > Conversion between different bases in Python

Conversion between different bases in Python

大家讲道理
Release: 2016-11-07 10:34:47
Original
1576 people have browsed it

Different bases

Binary 0b101

If a number starting with the number 0 and the letter b represents a binary number, a SyntaxError exception will be thrown if a number greater than or equal to 2 appears

Octal 0711

If a number starting with the number 0 represents an octal number A SyntaxError exception will be thrown when a number greater than or equal to 8 appears

Decimal 123

Letters cannot appear in normal display

Hex 0x15

Hexadecimal numbers beginning with the number 0 and subtitle x can appear 0-9 If any other value appears with abcdef or ABCDEF, a SyntaxError exception will be thrown.

Built-in function after python 2.6

#Convert decimal to binary

>>> bin(10)
'0b1010'
Copy after login

#Convert binary to decimal

>>> int("1001",2)
9
Copy after login

# Convert decimal to hexadecimal

>>> hex(10)
'0xa'
Copy after login

#16 to decimal

>>> int('ff', 16)
255
Copy after login
>>> int('0xab', 16)
171
Copy after login

#Convert decimal to octal

>>print("%o" % 10)
>>12
Copy after login

#16 to binary

>>> bin(0xa)
'0b1010'
>>>
Copy after login

# Decimal to octal

>>> oct(8)
'010'
Copy after login

#2 to hexadecimal

>>> hex(0b1001)
'0x9'
Copy after login

In addition, in the interactive interpreter environment, python will automatically convert different bases into decimals for calculations.

>>> 0b101 + 0711 + 123 + 0x15 
606
Copy after login
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template