从二进制文件创建十六进制文本文件 [英] Create text file of hexadecimal from binary

查看:265
本文介绍了从二进制文件创建十六进制文本文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想以某种格式将二进制文件转换为十六进制文件,并将其保存为文本文件。



最终产品应该是这样的:

p>

 \x7f\xe8\x89\x00\x00\x00\x60\x89\xe5 \x31\xd2\x64\x8b\x52

输入来自可执行文件文件a。
这是我当前的代码:

  with open('a','rb')as f:
byte = f.read(1)
hexbyte ='\\x%02s'%byte
print hexbyte

有几个问题:


  1. 这只打印第一个字节。
  2. >
  3. 结果是\x和一个如下所示的框:

00
7f



在终端中,它看起来像这样:



这是为什么?最后,如何将所有十六进制文件保存到文本文件中以获得上面显示的最终产品?

编辑:能够将文件另存为文本

  txt = open('out.txt','w')
print>> txt,hexbyte
txt.close()


解决方案

你不能将数字注入到这样的转义序列中。转义序列基本上是常量,因此它们不能有动态部分。

无论如何,已经有一个模块:

  from binascii以f:
print(hexlify(f.read())打开('test','rb')import hexlify
.decode('utf-8'))

只需在字节字符串上使用hexlify函数,会给你一个十六进制字节的字符串。您需要 decode 将其转换回普通字符串。



不太确定 decode 可以在Python 2中使用,但是您确实应该使用Python 3。


I would like to convert a binary to hexadecimal in a certain format and save it as a text file.

The end product should be something like this:

"\x7f\xe8\x89\x00\x00\x00\x60\x89\xe5\x31\xd2\x64\x8b\x52"

Input is from an executable file "a". This is my current code:

with open('a', 'rb') as f:
    byte = f.read(1)
    hexbyte = '\\x%02s' % byte
    print hexbyte

A few issues with this:

  1. This only prints the first byte.
  2. The result is "\x" and a box like this:

00 7f

In terminal it looks exactly like this:

Why is this so? And finally, how do I save all the hexadecimals to a text file to get the end product shown above?

EDIT: Able to save the file as text with

txt = open('out.txt', 'w')
print >> txt, hexbyte
txt.close()

解决方案

You can't inject numbers into escape sequences like that. Escape sequences are essentially constants, so, they can't have dynamic parts.

There's already a module for this, anyway:

from binascii import hexlify
with open('test', 'rb') as f:
  print(hexlify(f.read()).decode('utf-8'))

Just use the hexlify function on a byte string and it'll give you a hex byte string. You need the decode to convert it back into an ordinary string.

Not quite sure if decode works in Python 2, but you really should be using Python 3, anyway.

这篇关于从二进制文件创建十六进制文本文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆