简体   繁体   中英

Bitmask parsing in python using only standard library

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)

Arithmetic done elegantly, without C-style proceduralism:

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

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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM