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

Conversion between different bases in Python

大家讲道理
大家讲道理Original
2016-11-07 10:34:471594browse

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'

#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 to binary

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

# Decimal to octal

>>> oct(8)
'010'

#2 to hexadecimal

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

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

>>> 0b101 + 0711 + 123 + 0x15 
606
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