在Python中有任何罐装的Python方法将整数(或长)转换为二进制字符串吗?
谷歌上有无数的dec2bin()函数…但我希望我可以使用内置函数/库。
在Python中有任何罐装的Python方法将整数(或长)转换为二进制字符串吗?
谷歌上有无数的dec2bin()函数…但我希望我可以使用内置函数/库。
当前回答
你可以这样做:
bin(10)[2:]
or :
f = str(bin(10))
c = []
c.append("".join(map(int, f[2:])))
print c
其他回答
作为参考:
def toBinary(n):
return ''.join(str(1 & int(n) >> i) for i in range(64)[::-1])
这个函数可以将一个正整数一样大18446744073709551615,表示为字符串“1111111111111111111111111111111111111111111111111111111111111111”。
它可以被修改为一个更大的整数,尽管它可能不像"{0:b}".format()或bin()那么方便。
使用numpy pack/unpackbits,它们是你最好的朋友。
Examples
--------
>>> a = np.array([[2], [7], [23]], dtype=np.uint8)
>>> a
array([[ 2],
[ 7],
[23]], dtype=uint8)
>>> b = np.unpackbits(a, axis=1)
>>> b
array([[0, 0, 0, 0, 0, 0, 1, 0],
[0, 0, 0, 0, 0, 1, 1, 1],
[0, 0, 0, 1, 0, 1, 1, 1]], dtype=uint8)
def binary(decimal) :
otherBase = ""
while decimal != 0 :
otherBase = str(decimal % 2) + otherBase
decimal //= 2
return otherBase
print binary(10)
输出:
1010
除非我误解了你所说的二进制字符串,我认为你要找的模块是struct
这是针对python3的,它保持前导0 !
print(format(0, '08b'))