使用Python如何读取字节中的位? [英] Using Python How can I read the bits in a byte?

查看:431
本文介绍了使用Python如何读取字节中的位?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个文件,其中第一个字节包含编码信息.在Matlab中,我可以使用var = fread(file, 8, 'ubit1')一点一点地读取字节,然后通过var(1), var(2)等来检索每个比特.

I have a file where the first byte contains encoded information. In Matlab I can read the byte bit by bit with var = fread(file, 8, 'ubit1'), and then retrieve each bit by var(1), var(2), etc.

Python中是否有任何等效的读卡器?

Is there any equivalent bit reader in python?

推荐答案

从文件中读取位,低位在前.

Read the bits from a file, low bits first.

def bits(f):
    bytes = (ord(b) for b in f.read())
    for b in bytes:
        for i in xrange(8):
            yield (b >> i) & 1

for b in bits(open('binary-file.bin', 'r')):
    print b

这篇关于使用Python如何读取字节中的位?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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