Question

I want to parse an integer that is unpack()ed using the struct module to a list of truth values.

My current approach is this:

>>> [bool(int(_)) for _ in ("%8s" % str(bin(235)).split("b")[1]).replace(" ","0")]
[True, True, True, False, True, False, True, True]

It does the job, but is quite horribly convoluted. Anyone have an elegant and pythonesque way of doing the same?

Please note that above is just for an example and the bitmasks are not necessarily just 8 bits long, but the solution should work for an bitmask of arbitrary length (in practice it might be ok to just work with multiples of 4)

Was it helpful?

Solution

Arithmetic done elegantly, without C-style proceduralism:

size = 8
[bool(235 & (1 << size - i - 1)) for i in xrange(size)]

OTHER TIPS

How about:

>>> masklen = 8
>>> [bool(int(i)) for i in str(bin(235))[2:].rjust(masklen, '0')]
[True, True, True, False, True, False, True, True]

So if you skip pack step and just use the integer:

def bitboollist(v,n=0):
        l = []
        t = v
        while t != 0:
                l.append(bool(t % 2))
                t = t / 2
        l.reverse()
        if len(l) == 0:
                l = [False]
        if n > len(l):
                l = [False]*(n-len(l)) + l
        return l

using that on an example 1234 yields:

>>> bitboollist(1234)
[True, False, False, True, True, False, True, False, False, True, False]
>>> bitboollist(1234,n=16)
[False, False, False, False, False, True, False, False, True, True, False, True, False, False, True, False]
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top