Home  >  Article  >  Backend Development  >  Detailed explanation of conversion between different bases in Python

Detailed explanation of conversion between different bases in Python

高洛峰
高洛峰Original
2017-03-16 16:20:181607browse

Different bases

Binary 0b101

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

Octal 0711

Numbers starting with 0 represent octal numbers. If a number greater than or equal to 8 appears, a SyntaxError exception will be thrown

Decimal 123

Letters cannot appear in normal display

Hexadecimal 0x15

The hexadecimal number starting with the number 0 and the subtitle x can appear 0-9 and abcdef or ABCDEF will throw a SyntaxError exception when other values ​​appear

python After 2.6Built-in function

#Convert decimal to binary

>>> bin(10)
'0b1010'

#Convert binary to decimal

>>> int("1001",2)
9

#Convert decimal to hexadecimal

>>> hex(10)
'0xa'

#16 to decimal

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

#Convert decimal to octal

>>print("%o" % 10)
>>12

#16 base to binary system

>>> bin(0xa)
'0b1010'
>>>

#10 base system to 8 base system

>>> oct(8)
'010'

#2 base system to 16 base system

>>> hex(0b1001)
'0x9'

In addition, in the interactive In the interpreter environment, python will automatically convert different base systems into decimal systems for calculation.

>>> 0b101 + 0711 + 123 + 0x15 
606

The above is the detailed content of Detailed explanation of conversion between different bases in Python. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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