You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何读取Arduino提取的十六进制文件并转换为ASCII输出到文本文件

从Arduino十六进制文件恢复ASCII内容

问题背景

我从Arduino提取了十六进制格式的代码,想将其转换为ASCII以恢复上学期的项目代码。我仅熟悉C++,刚接触Python,给出的记录行示例:

:20 00E0 00 AC35B107D9F722E0ACE5B1E001C01D92A433B207E1F710E0C2E6D0E004C02197 D7

在Notepad++中,20是起始码,00E0是地址,末尾00是记录类型,D7是校验和,仅中间长串为有效数据,其余部分可丢弃。

我规划的处理步骤:

  • 打开包含十六进制代码的文件
  • 提取有效十六进制数据
  • 将十六进制转换为ASCII
  • 写入输出文件

我的现有代码存在问题,需要修正:

from math import ceil
import binascii
import tempfile
import os

# open the thing
f = open(" ", "r")

# read the thing
with open(os.path.abspath(f.name), 'r') as file:
    lines = file.readlines()
    hexLines = []
    for item in lines:
        hexLines.append(item.encode('utf-8').hex)
        binascii.unhexlify(hexLines)


# convert the thing
with tempfile.NamedTemporaryFile() as temp:
    print(hexLines)

# Write thing
g = open(" ", "w")
g.write('r')

修正后的Python代码

import binascii

# 替换为你的实际文件路径
input_file = "your_hex_file.txt"
output_file = "recovered_ascii.txt"

with open(input_file, 'r') as f_in, open(output_file, 'w') as f_out:
    for line in f_in:
        line = line.strip()
        if not line or not line.startswith(':'):
            continue
        
        # 按空格分割记录行,提取有效数据段
        parts = line.split()
        if len(parts) < 4:
            print(f"无效行: {line}")
            continue
        
        hex_data = parts[3]
        try:
            # 十六进制转二进制,再解码为ASCII(无法识别的字符用�替代)
            binary_data = binascii.unhexlify(hex_data)
            ascii_content = binary_data.decode('ascii', errors='replace')
            f_out.write(ascii_content)
        except binascii.Error as e:
            print(f"转换失败,行内容: {line},错误信息: {e}")

代码说明

  1. 文件路径配置:修改input_file和output_file为你实际的文件路径
  2. 行过滤与提取:
    • 跳过空行和非标准记录行
    • 按空格分割记录行,取出第4段的有效十六进制数据
  3. 转换逻辑:
    • 用binascii.unhexlify()将十六进制字符串转为二进制字节串
    • 用decode('ascii', errors='replace')将二进制转成ASCII,避免因不可识别字符导致程序中断
  4. 结果写入:直接将转换后的ASCII内容写入输出文件

重要提示

如果你提取的是Arduino编译后的机器码(十六进制形式),那么转换为ASCII后无法恢复原始C源码——机器码是编译后的二进制指令,逆向还原为可读的C代码难度极高,且无法完全还原。只有当你的十六进制是源码的十六进制编码时,转换才有意义。

内容的提问来源于stack exchange,提问作者TheMil

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.25 00:42:23