我怎样才能读取Python中的位? [英] How I can read a bit in Python?

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

问题描述

我知道如何读的字节(x.read(number_of_bytes)),但我怎么能在Python读取位?

I know how to read bytes (x.read(number_of_bytes)), but how can I read bits in Python?

我必须从二进制文件只读5位(不是8位[1个字节])

I have to read only 5 bits (not 8 bits[1 byte]) from a binary file

任何想法或做法?

推荐答案

Python中只能读取一次一个字节。你需要在一个完整的字节读,那么就提取您从字节所需的值,例如

Python can only read a byte at a time. You'd need to read in a full byte, then just extract the value you want from that byte, e.g.

b = x.read(1)
firstfivebits = b >> 3

或者,如果你想要的5至少显著位,而不是5个最显著位:

Or if you wanted the 5 least significant bits, rather than the 5 most significant bits:

b = x.read(1)
lastfivebits = b & 0b11111

一些其他有用的位操作信息可以在这里找到:<一href=\"http://wiki.python.org/moin/BitManipulation\">http://wiki.python.org/moin/BitManipulation

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

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