I\'ve created a method to convert an int
to a bitfield (in a list) and it works, but I\'m sure there is more elegant solution- I\'ve just been staring at it for to
This doesn't use bin
:
b = [n >> i & 1 for i in range(7,-1,-1)]
and this is how to handle any integer this way:
b = [n >> i & 1 for i in range(n.bit_length() - 1,-1,-1)]
See bit_length.
If you want index 0 of the list to correspond to the lsb of the int, change the range order, i.e.
b = [n >> i & 1 for i in range(0, n.bit_length()-1)]
Note also that using n.bit_length() can be a point of failure if you're trying to represent fixed length binary values. It returns the minimum number of bits to represent n.