This function receives as a parameter an integer and should return a list representing the same value expressed in binary as a list of bits, where the first element in the l
Not really the most efficient but at least it provides a simple conceptual way of understanding it...
1) Floor divide all the numbers by two repeatedly until you reach 1
2) Going in reverse order, create bits of this array of numbers, if it is even, append a 0 if it is odd append a 1.
Here's the literal implementation of that:
def intToBin(n):
nums = [n]
while n > 1:
n = n // 2
nums.append(n)
bits = []
for i in nums:
bits.append(str(0 if i%2 == 0 else 1))
bits.reverse()
print ''.join(bits)
Here's a version that better utilizes memory:
def intToBin(n):
bits = []
bits.append(str(0 if n%2 == 0 else 1))
while n > 1:
n = n // 2
bits.append(str(0 if n%2 == 0 else 1))
bits.reverse()
return ''.join(bits)
may I propose this:
def tobin(x,s):
return [(x>>k)&1 for k in range(0,s)]
it is probably the fastest way and it seems pretty clear to me. bin way is too slow when performance matters.
cheers
Convert integer to list of bits with a fixed length :
[int(x) for x in list('{0:0{width}b}'.format(8, width=5))]