在Python中有任何罐装的Python方法将整数(或长)转换为二进制字符串吗?
谷歌上有无数的dec2bin()函数…但我希望我可以使用内置函数/库。
在Python中有任何罐装的Python方法将整数(或长)转换为二进制字符串吗?
谷歌上有无数的dec2bin()函数…但我希望我可以使用内置函数/库。
当前回答
你可以这样做:
bin(10)[2:]
or :
f = str(bin(10))
c = []
c.append("".join(map(int, f[2:])))
print c
其他回答
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”
与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将是表示转换失败的哨兵值。(这是假设您只转换正数,无论它们是整数还是长数)。
对于那些需要将有符号整数(范围-2**(digits-1)到2**(digits-1)-1)转换为2的补码二进制字符串的人来说,这是可行的:
def int2bin(integer, digits):
if integer >= 0:
return bin(integer)[2:].zfill(digits)
else:
return bin(2**digits + integer)[2:]
这产生:
>>> int2bin(10, 8)
'00001010'
>>> int2bin(-10, 8)
'11110110'
>>> int2bin(-128, 8)
'10000000'
>>> int2bin(127, 8)
'01111111'
下面是一个使用divmod构造二进制列表的(调试)程序:
程序
while True:
indecimal_str = input('Enter positive(decimal) integer: ')
if indecimal_str == '':
raise SystemExit
indecimal_save = int(indecimal_str)
if indecimal_save < 1:
print('Rejecting input, try again')
print()
continue
indecimal = int(indecimal_str)
exbin = []
print(indecimal, '<->', exbin)
while True:
if indecimal == 0:
print('Conversion:', indecimal_save, '=', "".join(exbin))
print()
break
indecimal, r = divmod(indecimal, 2)
if r == 0:
exbin.insert(0, '0')
else:
exbin.insert(0, '1')
print(indecimal, '<->', exbin)
输出
Enter positive(decimal) integer: 8
8 <-> []
4 <-> ['0']
2 <-> ['0', '0']
1 <-> ['0', '0', '0']
0 <-> ['1', '0', '0', '0']
Conversion: 8 = 1000
Enter positive(decimal) integer: 63
63 <-> []
31 <-> ['1']
15 <-> ['1', '1']
7 <-> ['1', '1', '1']
3 <-> ['1', '1', '1', '1']
1 <-> ['1', '1', '1', '1', '1']
0 <-> ['1', '1', '1', '1', '1', '1']
Conversion: 63 = 111111
Enter positive(decimal) integer: 409
409 <-> []
204 <-> ['1']
102 <-> ['0', '1']
51 <-> ['0', '0', '1']
25 <-> ['1', '0', '0', '1']
12 <-> ['1', '1', '0', '0', '1']
6 <-> ['0', '1', '1', '0', '0', '1']
3 <-> ['0', '0', '1', '1', '0', '0', '1']
1 <-> ['1', '0', '0', '1', '1', '0', '0', '1']
0 <-> ['1', '1', '0', '0', '1', '1', '0', '0', '1']
Conversion: 409 = 110011001
如果你愿意放弃“纯”Python,但获得大量火力,这里有Sage -示例:
sage: a = 15
sage: a.binary()
'1111'
您将注意到它以字符串形式返回,因此要将它用作数字,您需要执行如下操作
sage: eval('0b'+b)
15