performing action on set of charecters

Paul Watson pwatson at redlinec.com
Fri Jan 23 02:46:14 EST 2004


"jeff" <gregadelliot at hotmail.com> wrote in message
news:cdac0350.0401220751.618353a3 at posting.google.com...
> hiya,
>
> Ive a load of binary in a file. Its 3 bit (2^3) and i wanna convert it
> to an integer.
>
> ive tried using theintergar = string.atoi(thebinary, 2), but that
> doesnt take it as 3 bit binary
>
> it has no spaces it it, so im a bit stuck as to how to do this with
> python,
>
> cheers
>
> greg

Will the following do what you want?

#! /usr/bin/env python

f = file('bits.dat', 'rb')
a = f.read()
f.close()

vals = []
for b in enumerate(a):
    v = ord(b[1])
    if (b[0] % 3) == 0:
        vals.append((v >> 5) & 0x07)
        vals.append((v >> 2) & 0x07)
        carryover = (v << 1) & 0x07
    if (b[0] % 3) == 1:
        vals.append(carryover | ((v >> 7) & 0x01))
        vals.append((v >> 4) & 0x07)
        vals.append((v >> 1) & 0x07)
        carryover = (v << 2) & 0x04
    if (b[0] % 3) == 2:
        vals.append(carryover | ((v >> 6) & 0x07))
        vals.append((v >> 3) & 0x07)
        vals.append(v & 0x07)

print vals





More information about the Python-list mailing list