Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
375 views
in Technique[技术] by (71.8m points)

python - Convert integer to binary array with suitable padding

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. Now 15 = 1111 in binary and so the output should be (1,1,1,1). 2 = 10 in binary and so the output should be (0,0,1,0). If m were 3 then 2 should be converted to (0,1,0).

I tried np.unpackbits(np.uint8(num)) but that doesn't give an array of the right length. For example,

np.unpackbits(np.uint8(15))
Out[5]: array([0, 0, 0, 0, 1, 1, 1, 1], dtype=uint8)

I would like a method that worked for whatever m I have in the code.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You should be able to vectorize this, something like

>>> d = np.array([1,2,3,4,5])
>>> m = 8
>>> (((d[:,None] & (1 << np.arange(m)))) > 0).astype(int)
array([[1, 0, 0, 0, 0, 0, 0, 0],
       [0, 1, 0, 0, 0, 0, 0, 0],
       [1, 1, 0, 0, 0, 0, 0, 0],
       [0, 0, 1, 0, 0, 0, 0, 0],
       [1, 0, 1, 0, 0, 0, 0, 0]])

which just gets the appropriate bit weights and then takes the bitwise and:

>>> (1 << np.arange(m))
array([  1,   2,   4,   8,  16,  32,  64, 128])
>>> d[:,None] & (1 << np.arange(m))
array([[1, 0, 0, 0, 0, 0, 0, 0],
       [0, 2, 0, 0, 0, 0, 0, 0],
       [1, 2, 0, 0, 0, 0, 0, 0],
       [0, 0, 4, 0, 0, 0, 0, 0],
       [1, 0, 4, 0, 0, 0, 0, 0]])

There are lots of ways to convert this to 1s wherever it's non-zero (> 0)*1, .astype(bool).astype(int), etc. I chose one basically at random.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...