将十六进制和 ASCII 字符解析为 Python 中的字符串

Parse hex and ASCII characters into string in Python

我有一个包含这样一行的文件:\x04\x01\x00\x00\x00\x00\x00{,我想像这样解析它:04:01:00:00:00:00:00:7b,其中 { 必须转换为十六进制({ = 7b).

我正在尝试构建一个小 python 脚本,但是将一些(不是全部)字符转换为十六进制的棘手部分对我来说很难。

这是我的开始方法:

def hex_parser(line):
    result = ''
    for l in line:
        if len(result):
            result = result + ':'
        if l != '\' or l != ',' or l != '\n':
            tmp_l = l.encode('utf8').hex()
            if len(tmp_l) == 1:
                tmp_l = '0' + tmp_l
            result = result + tmp_l
    return result

感谢您的帮助。

这一行将完成您的要求:

result = ":".join([f"{ord(hex_value):02X}" for hex_value in line if hex_value not in ['\','\n',',']])

这对行中的每个字符都适用,跳过列表中定义的字符:

  1. 使用 ord 转换为整数。 '\x00' = 0, '{' = 123
  2. 使用字符串格式转换为两位十六进制数

最后它获取列表并将每个部分连接成一个字符串,每个元素之间有一个 :

编辑:

这是一个函数,用于解析文本文件中包含实际十六进制表示形式 (\x00) 的行,从而生成类似于 python[=17= 中的 \x00 的字符串]

import re

def hex_parser(line):
    hex_values = []
    i = 0
    while i < len(line):
        if re.match("\\x[A-Fa-f0-9]{2}",line[i:i+4]):
            hex_values.append(line[i+2:i+4])
            i+= 4
        else:
            hex_values.append(f"{ord(line[i]):02X}")
            i += 1
    skip_values = [f"{ord(c):02X}" for c in ['\','\n',',']]
    return ":".join([h for h in hex_values if h not in skip_values])

尝试以二进制模式读取文件:

with open("file.txt", "rb") as f:
    for l in f.readlines(): # reads the file line by line
        print(":".join(["%02x"%ord(c) for c in l])) # go through each character and format it as hex string, put all together with ":" inbetween