Two 、 8、 ... and 、 Hexadecimal integer
problem
You need to convert or output using binary , An integer in octal or hexadecimal form .
solution
In order to convert integers to binary 、 Octal or hexadecimal text string , Can be used separately bin() , oct() or hex() function :
>>> x = 1234
>>> bin(x)
'0b10011010010'
>>> oct(x)
'0o2322'
>>> hex(x)
'0x4d2'
>>>
in addition , If you don't want to output 0b , 0o perhaps 0x The prefix of the word , have access to format() function . such as :
>>> format(x, 'b')
'10011010010'
>>> format(x, 'o')
'2322'
>>> format(x, 'x')
'4d2'
>>>
Integers are signed , So if you're dealing with negative numbers , The output will contain a negative sign . such as :
>>> x = -1234
>>> format(x, 'b')
'-10011010010'
>>> format(x, 'x')
'-4d2'
>>>
If you want to generate an unsigned value , You need to add a value indicating the maximum bit length . For example, to show 32 The value of a , You can write like this :
>>> x = -1234
>>> format(2**32 + x, 'b')
'11111111111111111111101100101110'
>>> format(2**32 + x, 'x')
'fffffb2e'
>>>
In order to convert integer strings in different bases , Simple to use with the base int() Function :
>>> int('4d2', 16)
1234
>>> int('10011010010', 2)
1234
>>>
Discuss
Most of the time, binary 、 Octal and hexadecimal integers are very simple . Just remember that these transformations are conversions between integers and their corresponding textual representations . There is always one integer type .
Last , Use octal programmers need to pay attention to . Python The syntax of octal is slightly different from that of other languages . such as , If you specify octal as follows , There will be grammatical errors :
>>> import os
>>> os.chmod('script.py', 0755)
File "<stdin>", line 1
os.chmod('script.py', 0755)
^
SyntaxError: invalid token
>>>
Make sure that the octal prefix is 0o , It looks like this :
>>> os.chmod('script.py', 0o755)
>>>