performing action on set of charecters

J

jeff

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
 
F

Francis Avila

jeff wrote in message ...
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

Three bit binary?! Whoever designed that format is a sadomasochist.

You're going to have to separate out the bits in the byte stream (so that
each bit is a byte--use strings), take three-bit groupings, and multiply to
convert to integer.

If this is a single, isolated three-bit integer, your approach will involve
shifting. If it's a continuous stream, without any padding, you can work in
groups of 24 bits (4 bytes), which gives you 8 3-bit ints.

There are many different approaches, but all will be painful. I don't think
it would be much easier in C, either (bit manipulation is often a little
easier in C compared to Python, albeit more dangerous).

Search this group. Not too long ago there was talk of a module for working
with binary which you might find helpful.
 
P

Paul Watson

jeff said:
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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,774
Messages
2,569,599
Members
45,165
Latest member
JavierBrak
Top