Integer to bitfield as a list

前端 未结 6 721
一向
一向 2021-02-13 01:33

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

6条回答
  •  误落风尘
    2021-02-13 02:10

    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.

提交回复
热议问题