您当前的位置:首页 > 计算机 > 编程开发 > Python

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

时间:09-08来源:作者:点击数:
CDSY,CDSY.XYZ
需求:
  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)

CDSY,CDSY.XYZ
方便获取更多学习、工作、生活信息请关注本站微信公众号城东书院 微信服务号城东书院 微信订阅号
推荐内容
相关内容
栏目更新
栏目热门
本栏推荐