Fastest way to convert a byte of integer into a list

Paul McGuire ptmcg at austin.rr.com
Fri Jul 13 06:17:22 EDT 2007


On Jul 12, 5:34 pm, Godzilla <godzillais... at gmail.com> wrote:
> Hello,
>
> I'm trying to find a way to convert an integer (8-bits long for
> starters) and converting them to a list, e.g.:
>
> num = 255
> numList = [1,1,1,1,1,1,1,1]
>
> with the first element of the list being the least significant, so
> that i can keep appending to that list without having to worry about
> the size of the integer. I need to do this because some of the
> function call can return a 2 lots of 32-bit numbers. I have to find a
> way to transport this in a list... or is there a better way?

Standing on the shoulders of previous posters, I put this together.

-- Paul


# init list of tuples by byte
bytebits = lambda num : [num >> i & 1 for i in range(8)]
bytes = [ tuple(bytebits(i)) for i in range(256) ]

# use bytes lookup to get bits in a 32-bit integer
bits = lambda num : sum((bytes[num >> i & 255] for i in range(0,32,8)),
())

# use base-2 log to find how many bits in an integer of arbitrary
length
from math import log,ceil
log_of_2 = log(2)
numBits = lambda num : int(ceil(log(num)/log_of_2))

# expand bits to integers of arbitrary length
arbBits = lambda num : sum((bytes[num >> i & 255] for i in
range(0,numBits(num),8)),())

print arbBits((1<<34)-1)
print arbBits(37)

# prints
#(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0)
#(1, 0, 1, 0, 0, 1, 0, 0)




More information about the Python-list mailing list