Recently, I was working on a course project of computer network course , To achieve reliable data transmission at the application layer , For transport layer UDP Unreliable channel . Because it involves the transmission of byte stream , So it is inevitable to use base conversion , After searching for information everywhere , The following methods are summarized . The following code has been tested in the command line window .
Use bin,oct,hex Can convert the numbers of other base numbers to binary respectively 、 octal 、 Hexadecimal .
>>> a = 50
>>> bin(a)
'0b110010'
>>> oct(a)
'0o62'
>>> hex(a)
'0x32'
>>> bin(a)[2:]
'110010'
Use int() You can convert any number to decimal .
>>> int('50', 10)
50
>>> int('0b110010', 2)
50
>>> int('0o62', 8)
50
>>> int('0x32', 16)
50
>>> int('110010', 2) # You don't have to have 0b Prefix
50
>>> int('50', 9) # Any base can be converted , such as 9
45
>>> format(a, 'd')
'50'
>>> format(a, 'b')
'110010'
>>> format(a, 'o')
'62'
>>> format(a, 'x')
'32'
>>> "{0:d}".format(50)
'50'
>>> "{0:b}".format(50)
'110010'
>>> "{0:o}".format(50)
'62'
>>> "{0:x}".format(50)
'32'
>>> "{0:08b}".format(50) # Specify a width of 8, Make up the deficiency in the front 0
'00110010'
About format If you have any questions, please refer to :Python format Format function
Although the above methods seem to have realized the conversion between hexadecimals , But it's all about the conversion between numbers and strings , Its memory space has changed accordingly . And to enable data to spread over the network , Just turn the data into a stream of data bytes , namely bytes.
>>> a = 50
>>> a.bit_length() # Check the bit length occupied by the number
6
# a=50, The corresponding binary is 110010, Two bytes are ‘00000000 00110010’,ascii In the encoding 50 The corresponding character is 2
>>> a.to_bytes(2, byteorder='little') # To 2 Bytes of bytes, Low in front
b'2\x00' # b‘\x00’ Express 0x00 namely 0b00000000,'2' yes ascii In the encoding 50 Corresponding characters
>>> a.to_bytes(2, byteorder='big') # To 2 Bytes of bytes, High up in the front
b'\x002'
>>> b = -50
>>> b.to_bytes(2, byteorder='little',signed=True) # Signed number
b'\xce\xff'
>>> b'\x002'[1] # For the first 1 Bytes b‘2’
50 # Output its utf-8 code ( Here with ASCII The code is the same , because ‘2’ You can use ASCII Coding means ,ASCII Coding can be seen as utf-8 Part of coding )
>>> b'\x002'[0] # For the first 0 Bytes b‘\x00’
0
>>> int.from_bytes(b'\x002', byteorder='big')
50
Yes bytes If you have any questions, please refer to : String and encoding