Representation and conversion of different bases in python

1. The base representation method in python

1. Binary representation method

The code is represented by 0b/0B in front of the binary code
as follows (example):

>>> a = 0b000010
>>> a
2
>>> a = 0B000010
>>> a
2

2. Octal notation method

Add 0o/0O in front of the octal to represent
the code as follows (example):

>>> 0o000010
8
>>> 0O000010
8

3. Hexadecimal notation

Add 0x/0X in front of the hexadecimal to indicate
the code as follows (example):

>>> 0x000010
16
>>> 0X000010
16

2. Binary conversion

1. Convert other bases to decimal

Directly use int for conversion
The following is the grammar description of int
class int(x, base = 10)

  • x – string or number.
  • base – the base number of x, the default is decimal.

提示:如果base不是10的话,x要以字符串的形式输入

class int(x, base=10)

(1) Convert binary to decimal

code example

>>> int('0b101',2)
5
>>> int('101',2)
5

(2) Octal to decimal

code example

>>> int('10',8)
8
>>> int('0o10',8)
8

(3) Hexadecimal to decimal

code example

>>> int('10',16)
16
>>> int('0x10',16)
16

2. Convert other bases to binary

bin(x)
is converted using the bin() function
bin(x) converts an integer to a binary string prefixed with "0b".

  • Parameter, pass in an integer, return the binary of the input parameter
  • Return value, returned as str string

先将要转换的数转成十进制然后再转成二进制

(1) Convert decimal to binary

>>> bin(10)
'0b1010'

(2) Octal to binary

>>> bin(int('7',8))
'0b111'

(3) Hexadecimal to binary

>>> bin(int('10',16))
'0b10000'

3. Convert other bases to octal

oct(int(n,8))
converts using the oct() function
bin(x) converts an integer to a binary string prefixed with "0o".

  • Parameters, pass in an integer, return the octal of the input parameter
  • Return value, returned as str string

先将要转换的数转成十进制然后再转成八进制

(1) Convert binary to octal

>>> oct(int('10',2))
'0o2'

(2) Decimal to octal

>>> oct(10)
'0o12'

(3) Hexadecimal to octal

>>> oct(int('0x10',16))
'0o20'

4. Other base to hexadecimal

hex(int(n,8))
converts using the hex() function
hex(x) converts an integer to a binary string prefixed with "0x".

  • Parameters, pass in an integer, return the octal of the input parameter
  • Return value, returned as str string

先将要转换的数转成十进制然后再转成十六进制

(1) Binary to hexadecimal

>>> hex(int('0b11',2))
'0x3'

(2) Octal to hexadecimal

>>> hex(int('0o17',8))
'0xf'

(3) Decimal to hexadecimal

>>> hex(10)
'0xa'

For conversion between data types, please refer to the following article: Python data type conversion int(), float(), eval() functions

Guess you like

Origin blog.csdn.net/qq_43589852/article/details/127897672