操纵在Python中的二进制数据 [英] Manipulating binary data in Python

查看:107
本文介绍了操纵在Python中的二进制数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我打开一个二进制文件,像这样:

I am opening up a binary file like so:

file = open("test/test.x", 'rb')

和在线条列表中读取。每一行看起来有点像:

and reading in lines to a list. Each line looks a little like:

'\xbe\x00\xc8d\xf8d\x08\xe4.\x07~\x03\x9e\x07\xbe\x03\xde\x07\xfe\n'

我有一个很难操纵这些数据。如果我尝试并打印每一行,蟒蛇冻结,并发出蜂鸣噪声(我觉得有一个二进制哔code在某处)。我怎么去安全地使用这些数据?我怎么能相互转换的十六进制数到十进制?

I am having a hard time manipulating this data. If I try and print each line, python freezes, and emits beeping noises (I think there's a binary beep code in there somewhere). How do I go about using this data safely? How can I convert each hex number to decimal?

推荐答案

要打印,你可以做这样的事情:

To print it, you can do something like this:

print repr(data)

有关整件事为十六进制:

For the whole thing as hex:

print data.encode('hex')

对于每个字节的十进制值:

For the decimal value of each byte:

print ' '.join([str(ord(a)) for a in data])

要解压二进制整数,等等。从数据就好像它最初是从C风格的结构来了,看结构模块。

To unpack binary integers, etc. from the data as if it originally came from a C-style struct, look at the struct module.

这篇关于操纵在Python中的二进制数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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