Conversion between commonly used decimal, hexadecimal, string, and byte string in python (updated for a long time)
During protocol parsing, you will always encounter various data conversion problems, from binary to decimal, from byte string to integer, etc.
Not much nonsense. Let's look at the example directly.
Hexadecimal conversion between integers:
10 to 16: hex (16) => 0x1016 to 10: int ('0x10', 16) ==> 16 Similar oct (), bin ()
-------------------
String to integer:
10 hexadecimal string: int ('10') ==> 1016 hexadecimal string: int ('10', 16) ==> 1616 hexadecimal string: int ('0x10', 16) => 16
-------------------
Byte string to integer:
Escape as a short INTEGER: struct. unpack (' (1, 0) escape as a long integer: struct. unpack (' (1 ,)
-------------------
Integer to byte string:
Convert to two bytes: struct. pack (' B '\ x01 \ x00 \ x02 \ x00' is converted into four bytes: struct. pack (' B '\ x01 \ x00 \ x00 \ x00 \ x02 \ x00 \ x00 \ x00'
-------------------
String to byte string:
The string is encoded as a bytecode: '12abc '. encode ('ascii ') => B '12abc' number or character array: bytes ([1, 2, ord ('1'), ord ('2')]) ==> B '\ x01 \ x0212' hexadecimal string: bytes (). fromhex ('000000') ==> B '\ x01 \ x02 \ x10' hexadecimal string: bytes (map (ord, '\ x01 \ x02 \ x31 \ x32') ==> B '\ x01 \ x0212 'hexadecimal array: bytes ([0x01,0x02,0x31,0x32]) ==> B '\ x01 \ x0212'
-------------------
Byte string to string:
The bytecode is decoded as a string: bytes (B '\ x31 \ x32 \ x61 \ x62 '). decode ('ascii ') ==> 12ab byte string to hexadecimal representation, carrying ascii: str (bytes (B' \ x01 \ x0212 ') [2: -1] ==>\x01 \ x0212 byte string to hexadecimal representation, fixed two characters: str (binascii. b2a_hex (B '\ x01 \ x0212') [2:-1] ==> 01023132 byte string to hexadecimal array: [hex (x) for x in bytes (B '\ x01 \ x0212')] ==> ['0x1 ', '0x2', '0x31', '0x32']
==============================
Python source code for testing
'''Created on August 21, 2014 @ author: lenovo ''' import binasciiimport structdef example (express, result = None): if result = None: result = eval (express) print (express, '=>', result) if _ name _ = '_ main _': print ('hexadecimal conversion between integers :') print ("hexadecimal to hexadecimal", end = ':'); example ("hex (16)") print ("hexadecimal to hexadecimal ", end = ':'); example ("int ('0x10', 16)") print ("similar to oct (), bin ()") print ('\ n ----------------- \ n') print ('string to integer:') print ("10 hexadecimal string", end = ":"); example ("int ('10')") print ("hexadecimal string", end = ":"); example ("int ('10', 16 )") print ("hexadecimal string", end = ":"); example ("int ('0x10', 16)") print ('\ n ----------------- \ n ') print ('byte string to integer: ') print ("escape to short type Integer", end = ":"); example (r "struct. unpack ('
The above principles are relatively simple. You can see it at a glance. Here is just a reference, and there are better and simpler methods. Welcome.