Convert integer to binary array with suitable padding

后端 未结 4 1609
不思量自难忘°
不思量自难忘° 2020-12-05 20:29

I have integers in the range 0..2**m - 1 and I would like to convert them to binary numpy arrays of length m. For example, say m = 4.

4条回答
  •  再見小時候
    2020-12-05 20:56

    Seems like you could just modify the resulting array. I don't know the function exactly, but most implementations like np.unpackbits would not inherently know the size of the number - python ints can be arbitrarily large, after all, and don't have a native size.

    However, if you know m, you can easily 'fix' the array. Basically, an unpack function will give you some number of bits (that is a multiple of 8) for the byte with the highest 1 in the number. You just need to remove extra 0s, or prepend 0s, to get the right distance:

    m = 4
    mval = np.unpackbits(np.uint8(15))
    
    if len(mval) > m:
       mval = mval[m-len(mval):]
    elif m > len(mval):
       # Create an extra array, and extend it
       mval = numpy.concatenate([numpy.array([0]*(m-len(mval)), dtype=uint8), mval])
    

提交回复
热议问题