reading single bits?
Carlos Ribeiro
carribeiro at yahoo.com
Sat Mar 24 16:46:12 EST 2001
At 15:40 24/03/01 +0100, Alex Berger wrote:
>How can I read/write single bits of some binary data when I know the
>position??
Let's divide the problem in two. First you need to read the information
from the file object. This can be done by opening the file in binary mode,
seeking to the desired position and reading the information. But (on most
modern filesystems) files are composed of *bytes*, not bits. So you are
going to read one byte, not one bit. You have to account for this
difference when seeking, dividing the offset by 8 to get to the position.
The modulus of this division is the position of the bit inside the byte.
For example, lets assume that you want to red the bit 35:
35 div 8 = 4 (position of the byte inside the file)
35 mod 8 = 3 (position of the bit inside the byte)
Some example code:
>>> f = open('myfile', 'rb')
>>> f.seek(position div 8)
>>> c = int(f.read(1))
Now you have a single byte, preferably represented as a integer (in other
languages, the data type name may be different - byte in Pascal, char or
shortint in C...). In order to extract a single bit, you use binary
arithmetic operations. Let's c be the byte you read on the first step, and
b the bit number (from 0 to 7):
Read : bit = (c and (1 * (2 ** b))) != 0
Write: c = c or (bit * (2 ** b))
The basic idea is to generate a binary mask for the bit you want to
read/write, and then use binary operations over the byte. There are other
ways to achieve the same goal more efficiently. The most popular is using
"<<" - the "shift left" operator. Shifting 1 to the left is equivalent to
the 2**b operation, and makes for a slightly simpler solution:
Read : bit = (c and (1 << b)) != 0
Write: c = c or (bit << b)
Please note that these techniques apply to most languages and operating
systems (I cant remember of a single example in modern environments where
it does not works). Some details may be different. For instance, the !=
logical operator returns 1 or 0 in Python. Some other languages may have
different behavior.
This is a very basic tutorial, and several simplifications are possible.
Carlos Ribeiro
_________________________________________________________
Do You Yahoo!?
Get your free @yahoo.com address at http://mail.yahoo.com
More information about the Python-list
mailing list