python读取二进制文件,转成十六进制格式

需求:

  1. 读取二进制(bytes)的文件
  2. 转换为十六进制(hex),保存到txt纯文本文件里
  3. 从纯文本文件搜索某个字符串,如ffff00
无需安装第三方库,使用内置库binascii即可
  • analysis.py
#!/usr/bin python3
# -*- coding: utf-8 -*-

import binascii


def analysis(bin_path: str, out_txt_path: str):
    with open(bin_path, 'rb') as f:
    	# 读取全部行
        all_data = f.readlines()
        
        with open(out_txt_path, 'a+') as new_f:
            for i in all_data:
            	# 二进制(bytes)类型转换成十六进制类型
                hex_str = binascii.b2a_hex(i).decode('unicode_escape')
                # 以str格式逐行写入到文本
                new_f.write(str(hex_str) + '\n')
        print("解析完成")


if __name__ == '__main__':
    input_file_path = "./kill.bin"
    out_file_path = "./hex_of_kill.txt"
    analysis(input_file_path, out_file_path)
  • find.py
#!/usr/bin python3
# -*- coding: utf-8 -*-

def search(txt_path: str, key_word: str, target_segment_length: int):
    target_txt_dict = {}
    target_result_list = []
    state = False
    with open(txt_path) as f:
        for index, line in enumerate(f.readlines()):
            if key_word in line:
                target_txt_dict[index + 1] = line
                state = True
    # print(target_txt_dict)
    if not state:
        print(f"未在文件中发现{key_word}")
    else:
        for k, v in target_txt_dict.items():
            if v.find(key_word) != -1:
                find_start_index = 0
                while 1:
                    target_txt_index = v.find(key_word, find_start_index)
                    segment_start_index = target_txt_index + len(key_word)
                    target_data = v[segment_start_index:segment_start_index + target_segment_length]
                    target_result_list.append(target_data)
                    find_start_index = segment_start_index

                    if v.find(key_word, find_start_index) == -1:
                        break

        print(target_result_list)
    print("查找完成")


if __name__ == '__main__':
    search_txt = 'ffff00'
    file_path = "./hex_of_kill.txt"
    search(file_path, search_txt, 16)

  • 5
    点赞
  • 28
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

木法星人

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值