十六进制转储文件的pythonic方法

编程入门 行业动态 更新时间:2024-10-26 00:28:59
本文介绍了十六进制转储文件的pythonic方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我的问题很简单:

有什么方法可以通过bash命令的pythonic方式进行编码吗?

Is there any way to code in a pythonic way that bash command?

hexdump -e '2/1 "%02x"' file.dat

很明显,没有使用os,popen或任何快捷方式;)

Obviously, without using os, popen, or any shortcut ;)

尽管我没有明确指定,但是如果代码在Python3.x中可以正常工作,那就太好了

although I've not explicitly specified, it would be great if the code was functional in Python3.x

谢谢!

推荐答案

如果您只关心Python 2.x,请 line.encode('hex') 会将二进制数据块编码为十六进制.所以:

If you only care about Python 2.x, line.encode('hex') will encode a chunk of binary data into hex. So:

with open('file.dat', 'rb') as f: for chunk in iter(lambda: f.read(32), b''): print chunk.encode('hex')

(默认情况下,IIRC,hexdump每行打印32对十六进制;如果没有,只需将32更改为16或其他内容……)

(IIRC, hexdump by default prints 32 pairs of hex per line; if not, just change that 32 to 16 or whatever it is…)

如果两个参数 iter 看起来莫名其妙,请单击帮助链接;一旦您有了主意,它就不会太复杂.

如果您关心Python 3.x,请 encode

If you care about Python 3.x, encode only works for codecs that convert Unicode strings to bytes; any codecs that convert the other way around (or any other combination), you have to use codecs.encode to do it explicitly:

with open('file.dat', 'rb') as f: for chunk in iter(lambda: f.read(32), b''): print(codecs.encode(chunk, 'hex'))

或者最好使用 hexlify :

Or it may be better to use hexlify:

with open('file.dat', 'rb') as f: for chunk in iter(lambda: f.read(32), b''): print(binascii.hexlify(chunk))

如果您除了打印输出外还想做些其他事情,而不是将整个文件读入内存,您可能想要创建一个迭代器.您可以将其放在函数中,然后将print更改为yield,该函数将恰好返回您想要的迭代器.或使用genexpr或map呼叫:

If you want to do something besides print them out, rather than read the whole file into memory, you probably want to make an iterator. You could just put this in a function and change that print to a yield, and that function returns exactly the iterator you want. Or use a genexpr or map call:

with open('file.dat', 'rb') as f: chunks = iter(lambda: f.read(32), b'') hexlines = map(binascii.hexlify, chunks)

更多推荐

十六进制转储文件的pythonic方法

本文发布于:2023-10-28 19:54:06,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1537616.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:方法   十六进制转   储文   pythonic

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!