I know how to read bytes — x.read(number_of_bytes), but how can I read bits in Python?
I have to read only 5 bits (not 8 bits [1 byte]) from a binary file
Any ideas or approach?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
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.
Or if you wanted the 5 least significant bits, rather than the 5 most significant bits:
Some other useful bit manipulation info can be found here: http://wiki.python.org/moin/BitManipulation