在Python中有任何罐装的Python方法将整数(或长)转换为二进制字符串吗?
谷歌上有无数的dec2bin()函数…但我希望我可以使用内置函数/库。
在Python中有任何罐装的Python方法将整数(或长)转换为二进制字符串吗?
谷歌上有无数的dec2bin()函数…但我希望我可以使用内置函数/库。
当前回答
有点类似的解决方案
def to_bin(dec):
flag = True
bin_str = ''
while flag:
remainder = dec % 2
quotient = dec / 2
if quotient == 0:
flag = False
bin_str += str(remainder)
dec = quotient
bin_str = bin_str[::-1] # reverse the string
return bin_str
其他回答
numpy。binary_repr(全国矿工工会,width = band)
例子来自上面的文档链接:
> > > np.binary_repr (3) “11” > > > np.binary_repr (3) “-11” > > > np。binary_repr(宽度= 4) “0011” 当输入数字为负数并且指定width时,返回2的补数: > > > np。binary_repr(3、宽度= 3) “101” > > > np。binary_repr(宽度= 5) “11101”
备选方案总结:
n=42
assert "-101010" == format(-n, 'b')
assert "-101010" == "{0:b}".format(-n)
assert "-101010" == (lambda x: x >= 0 and str(bin(x))[2:] or "-" + str(bin(x))[3:])(-n)
assert "0b101010" == bin(n)
assert "101010" == bin(n)[2:] # But this won't work for negative numbers.
贡献者包括John Fouhy, Tung Nguyen, mVChr, Martin Thoma。还有马丁·彼得斯。
def binary(decimal) :
otherBase = ""
while decimal != 0 :
otherBase = str(decimal % 2) + otherBase
decimal //= 2
return otherBase
print binary(10)
输出:
1010
计算二进制数:
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
这是另一种使用常规数学的方法,没有循环,只有递归。(琐碎情况0不返回任何内容)。
def toBin(num):
if num == 0:
return ""
return toBin(num//2) + str(num%2)
print ([(toBin(i)) for i in range(10)])
['', '1', '10', '11', '100', '101', '110', '111', '1000', '1001']