簡體   English   中英

在Python中將十六進制和ASCII字符解析為字符串

[英]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腳本,但是將一些(不是全部)字符轉換為十六進制的棘手部分對我來說很難。

這是我的beginnig方法:

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中生成類似\\\\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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM