Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read bits from a file?

Tags:

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?

like image 433
Hugo Medina Avatar asked May 21 '12 17:05

Hugo Medina


People also ask

How do you read a binary file as a bit?

Read the first two bytes from your a_file file pointer and check the bits in the least or greatest byte — depending on the endianness of your platform (x86 is little-endian) — using bitshift operators. You can't really put bits into an array, as there isn't a datatype for bits.

How do I read a binary bit by bit in Python?

Python Read Binary File into Byte Array First, the file is opened in the“ rb “ mode. A byte array called mybytearray is initialized using the bytearray() method. Then the file is read one byte at a time using f. read(1) and appended to the byte array using += operator.

How do I read a binary file in Python?

To open a file in binary format, add 'b' to the mode parameter. Hence the "rb" mode opens the file in binary format for reading, while the "wb" mode opens the file in binary format for writing. Unlike text files, binary files are not human-readable. When opened using any text editor, the data is unrecognizable.


1 Answers

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

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

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

Some other useful bit manipulation info can be found here: http://wiki.python.org/moin/BitManipulation

like image 159
Amber Avatar answered Mar 27 '23 02:03

Amber