简体   繁体   English

如何将 integer 转换为其二进制表示形式为 numpy 数组?

[英]How can I convert an integer to its binary representation as a numpy array?

I'm interested in taking a single integer and converting it to a numpy array of 1's and 0's equal to the number's binary representation.我有兴趣采用单个 integer 并将其转换为 numpy 数组,其中 1 和 0 等于数字的二进制表示。 I'd like to fix the length of the array (pad with zeros as needed) while I'm at it.我想在我处理数组时修复数组的长度(根据需要用零填充)。 How can this been done?这是怎么做到的?

Something along these lines:这些方面的东西:

>>> func(19,bits=7)
np.array([0,0,1,0,0,1,1])

Use Python's bin() for binary conversion使用 Python 的bin()进行二进制转换

def func(x, bits):
    return np.array([int(i) for i in bin(x)[2:].zfill(bits)])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM