FAQ
"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

Search Discussions

Discussion Posts

Previous

Related Discussions

Discussion Navigation
viewthread | post
posts ‹ prev | 3 of 3 | next ›
Discussion Overview
grouppython-list @
categoriespython
postedJan 22, '04 at 3:51p
activeJan 23, '04 at 7:46a
posts3
users3
websitepython.org

People

Translate

site design / logo © 2022 Grokbase