Python中的文件中获取原始二进制重新presentation [英] Getting Raw Binary Representation of a file in Python

查看:136
本文介绍了Python中的文件中获取原始二进制重新presentation的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从文件中得到位的确切顺序为使用Python 3.有关于这一主题而接近,但不太回答几个问题的字符串。到目前为止,我有这样的:

I'd like to get the exact sequence of bits from a file into a string using Python 3. There are several questions on this topic which come close, but don't quite answer it. So far, I have this:

>>> data = open('file.bin', 'rb').read()
>>> data
'\xa1\xa7\xda4\x86G\xa0!e\xab7M\xce\xd4\xf9\x0e\x99\xce\xe94Y3\x1d\xb7\xa3d\xf9\x92\xd9\xa8\xca\x05\x0f$\xb3\xcd*\xbfT\xbb\x8d\x801\xfanX\x1e\xb4^\xa7l\xe3=\xaf\x89\x86\xaf\x0e8\xeeL\xcd|*5\xf16\xe4\xf6a\xf5\xc4\xf5\xb0\xfc;\xf3\xb5\xb3/\x9a5\xee+\xc5^\xf5\xfe\xaf]\xf7.X\x81\xf3\x14\xe9\x9fK\xf6d\xefK\x8e\xff\x00\x9a>\xe7\xea\xc8\x1b\xc1\x8c\xff\x00D>\xb8\xff\x00\x9c9...'

>>> bin(data[:][0])
'0b11111111'

好吧,我可以得到一个二进制数,但我不明白为什么数据[:] [X],我仍然有领先0B。这也似乎是我必须通过整个字符串循环,并做一些铸造和解析,以获得正确的输出。有没有一种简单的方法来只得到01的序列不用循环,解析和连接字符串?

OK, I can get a base-2 number, but I don't understand why data[:][x], and I still have the leading 0b. It would also seem that I have to loop through the whole string and do some casting and parsing to get the correct output. Is there a simpler way to just get the sequence of 01's without looping, parsing, and concatenating strings?

在此先感谢!

推荐答案

我先precompute字符串重新presentation所有值0..255

I would first precompute the string representation for all values 0..255

bytetable = [("00000000"+bin(x)[2:])[-8:] for x in range(256)]

或者,如果你在preFER位LSB到MSB

or, if you prefer bits in LSB to MSB order

bytetable = [("00000000"+bin(x)[2:])[-1:-9:-1] for x in range(256)]

然后在二进制整个文件可以用获得

then the whole file in binary can be obtained with

binrep = "".join(bytetable[x] for x in open("file", "rb").read())

这篇关于Python中的文件中获取原始二进制重新presentation的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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