Efficient Bit addressing in Python.
Ross Ridge
rridge at csclub.uwaterloo.ca
Fri Oct 10 05:57:46 EDT 2008
Hendrik van Rooyen <mail at microcorp.co.za> wrote:
>Is there a canonical way to address the bits in a structure
>like an array or string or struct?
>
>Or alternatively, is there a good way to combine eight
>ints that represent bits into one of the bytes in some
>array or string or whatever?
This is the code I use to convert large bit arrays to byte strings and
back:
import string
import binascii
import array
_tr_16 = string.maketrans("0123456789abcdef",
"\x00\x01\x02\x03"
"\x10\x11\x12\x13"
"\x20\x21\x22\x23"
"\x30\x31\x32\x33")
_tr_4 = string.maketrans("0123",
"\x00\x01"
"\x10\x11")
_tr_2 = string.maketrans("01", "\x00\x01")
def string_to_bit_array(s):
"""Convert a string to an array containing a sequence of bits."""
s = binascii.hexlify(s).translate(_tr_16)
s = binascii.hexlify(s).translate(_tr_4)
s = binascii.hexlify(s).translate(_tr_2)
a = array.array('B', s)
return a
_tr_rev_2 = string.maketrans("\x00\x01", "01")
_tr_rev_4 = string.maketrans("\x00\x01"
"\x10\x11",
"0123")
_tr_rev_16 = string.maketrans("\x00\x01\x02\x03"
"\x10\x11\x12\x13"
"\x20\x21\x22\x23"
"\x30\x31\x32\x33",
"0123456789abcdef")
def bit_array_to_string(a):
"""Convert an array containing a sequence of bits to a string."""
remainder = len(a) % 8
if remainder != 0:
a.fromlist([0] * (8 - remainder))
s = a.tostring()
s = binascii.unhexlify(s.translate(_tr_rev_2))
s = binascii.unhexlify(s.translate(_tr_rev_4))
return binascii.unhexlify(s.translate(_tr_rev_16))
I don't think you can do anything faster with standard modules, although
it might not be effecient if you're only working with a single byte.
Ross Ridge
--
l/ // Ross Ridge -- The Great HTMU
[oo][oo] rridge at csclub.uwaterloo.ca
-()-/()/ http://www.csclub.uwaterloo.ca/~rridge/
db //
More information about the Python-list
mailing list