There is a task at the entrance to the script Hex code ( "7200F40004226301" ). This code into a variable is read in the list format, and each character has an extension like str, and it is necessary that the script could work with the symbol as with a number.

 for item in content: for symbol in item: k = int(''.join("%02X " % ord( symbol ))) 

result:

 >> symbol 7 >>> type(symbol) <class 'str'> >>> type(k) <class 'int'> >>> k 37 >>> hex(k) '0x25' 

But I want to make hex(k) = 0x07 , not 0x25 . Perhaps I initially chose the wrong way to solve the problem, since I am a layman in programming.

  • tell what, where? - Flowneee
  • I disassembled this string character by character and I need to make it clear to the python that each character is already in the 16th hex format - Gennadiy_G
  • one
    In python, there is no type of number in the hexadecimal number system. These numbers are represented as a string starting with 0x . - mkkik
  • one
    Show the result: print(ascii(ваша_строка)) . What do you want to get as a result (type, value)? Explicitly an example of input output using Python syntax show. - jfs
  • one
    The comment was clearer. If you read from the file and write the modified content to the file, then show a few bytes from the input file and by which ones and by what rule you want to replace them. Do not put the information necessary for the answer in the comments, edit your question instead (and add the code with normal formatting). If you think that you have found a solution, then publish it as your answer — this is clearly welcome . Perhaps you binascii.unhexlify () will help. - jfs

2 answers 2

If you open a file as text (for example, in a notepad), you see the line 7200F40004226301 (hexadecimal numbers in the text — Unicode characters: 7 ( U + 0037 DIGIT SEVEN ), 2 ( U + 0032 DIGIT TWO ), 0 ( U + 0030 DIGIT ZERO ), etc.) the so-called hexdump (bytes -> hex) , then to perform the inverse transformation (hex -> bytes) and get the original byte sequence: 0x72, 0x00, 0xF4, ... like the type bytes in Python:

 >>> import binascii >>> binascii.unhexlify("7200F40004226301") # из hex-строки в bytes b'r\x00\xf4\x00\x04"c\x01' >>> list(_) [114, 0, 244, 0, 4, 34, 99, 1] >>> b'r'[0] # индексация bytes возвращает индивидуальные байты (int) 114 >>> int("72", 16) # из hex-строки в int 114 >>> 0x72 == 114 == 0b1110010 # одно и то же число в разных системах исчисления True 

In the text of the Python program, the bytes that correspond to the printed ASCII characters can be represented as these characters, so 114 bytes is printed as text as b'r' , and not b'\x72' as other bytes. See Bytes - translation from string .

    If I understood the question correctly, then at the input you get binary encoded data in hex. To obtain a byte array from such a view, there is a function binascii.unhexlify