在Python中有任何罐装的Python方法将整数(或长)转换为二进制字符串吗?
谷歌上有无数的dec2bin()函数…但我希望我可以使用内置函数/库。
在Python中有任何罐装的Python方法将整数(或长)转换为二进制字符串吗?
谷歌上有无数的dec2bin()函数…但我希望我可以使用内置函数/库。
当前回答
如果你愿意放弃“纯”Python,但获得大量火力,这里有Sage -示例:
sage: a = 15
sage: a.binary()
'1111'
您将注意到它以字符串形式返回,因此要将它用作数字,您需要执行如下操作
sage: eval('0b'+b)
15
其他回答
这是我的答案,它工作得很好…!
def binary(value) :
binary_value = ''
while value !=1 :
binary_value += str(value%2)
value = value//2
return '1'+binary_value[::-1]
Python的字符串格式方法可以接受格式规范。
>>> "{0:b}".format(37)
'100101'
Python 2的格式规范文档
Python 3的格式规范文档
下面是一个使用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
使用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)
如果你愿意放弃“纯”Python,但获得大量火力,这里有Sage -示例:
sage: a = 15
sage: a.binary()
'1111'
您将注意到它以字符串形式返回,因此要将它用作数字,您需要执行如下操作
sage: eval('0b'+b)
15