在Python中有任何罐装的Python方法将整数(或长)转换为二进制字符串吗?
谷歌上有无数的dec2bin()函数…但我希望我可以使用内置函数/库。
在Python中有任何罐装的Python方法将整数(或长)转换为二进制字符串吗?
谷歌上有无数的dec2bin()函数…但我希望我可以使用内置函数/库。
当前回答
一个简单的方法是使用字符串格式,请参阅本页。
>> "{0:b}".format(10)
'1010'
如果你想要一个固定长度的二进制字符串,你可以使用这个:
>> "{0:{fill}8b}".format(10, fill='0')
'00001010'
如果需要使用two的补码,那么可以使用下面的行:
'{0:{fill}{width}b}'.format((x + 2**n) % 2**n, fill='0', width=n)
其中n是二进制字符串的宽度。
其他回答
与Yusuf Yazici的回答相似
def intToBin(n):
if(n < 0):
print "Sorry, invalid input."
elif(n == 0):
print n
else:
result = ""
while(n != 0):
result += str(n%2)
n /= 2
print result[::-1]
我调整了它,使唯一被改变的变量是结果(当然还有n)。
如果你需要在其他地方使用这个函数(即,让结果被另一个模块使用),考虑以下调整:
def intToBin(n):
if(n < 0):
return -1
elif(n == 0):
return str(n)
else:
result = ""
while(n != 0):
result += str(n%2)
n //= 2 #added integer division
return result[::-1]
因此-1将是表示转换失败的哨兵值。(这是假设您只转换正数,无论它们是整数还是长数)。
使用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)
try:
while True:
p = ""
a = input()
while a != 0:
l = a % 2
b = a - l
a = b / 2
p = str(l) + p
print(p)
except:
print ("write 1 number")
计算二进制数:
print("Binary is {0:>08b}".format(16))
计算一个数的十六进制小数:
print("Hexa Decimal is {0:>0x}".format(15))
计算所有的二进制直到16::
for i in range(17):
print("{0:>2}: binary is {0:>08b}".format(i))
要计算十六进制小数,直到17
for i in range(17):
print("{0:>2}: Hexa Decimal is {0:>0x}".format(i))
##as 2 digit is enogh for hexa decimal representation of a number
这是针对python3的,它保持前导0 !
print(format(0, '08b'))