How to Read Bytes from a file
B.Ogryczak at gmail.com
Fri Mar 2 12:22:36 CET 2007
On Mar 1, 7:36 pm, "gregpin... at gmail.com" <gregpin... at gmail.com>
> On Mar 1, 12:46 pm, "Bart Ogryczak" <B.Ogryc... at gmail.com> wrote:
> > > This solution looks nice, but how does it work? I'm guessing
> > > struct.unpack will provide me with 8 bit bytes
> > unpack with 'B' format gives you int value equivalent to unsigned char
> > (1 byte).
> > > (will this work on any system?)
> > Any system with 8-bit bytes, which would mean any system made after
> > 1965. I'm not aware of any Python implementation for UNIVAC, so I
> > wouldn't worry ;-)
> > > How does count1 work exactly?
> > 1,2,4,8,16,32,64,128 in binary are
> > 1,10,100,1000,10000,100000,1000000,10000000
> > x&1 == 1 if x has first bit set to 1
> > x&2 == 2, so (x&2>0) == True if x has second bit set to 1
> > ... and so on.
> > In the context of int, True is interpreted as 1, False as 0.
> Thanks Bart. That's perfect. The other suggestion was to precompute
> count1 for all possible bytes, I guess that's 0-256, right?
0-255 actually. It'd be worth it, if accessing dictionary with
precomputed values would be significantly faster then calculating the
lambda, which I doubt. I suspect it actually might be slower.
More information about the Python-list