在Python中有任何罐装的Python方法将整数(或长)转换为二进制字符串吗?
谷歌上有无数的dec2bin()函数…但我希望我可以使用内置函数/库。
在Python中有任何罐装的Python方法将整数(或长)转换为二进制字符串吗?
谷歌上有无数的dec2bin()函数…但我希望我可以使用内置函数/库。
当前回答
由于前面的答案大多使用format(), 这是一个f字符串的实现。
integer = 7
bit_count = 5
print(f'{integer:0{bit_count}b}')
输出:
00111
为了方便起见,这里有python文档中格式化字符串文字的链接:https://docs.python.org/3/reference/lexical_analysis.html#f-strings。
其他回答
这是另一种算法的解决方案,使用位运算符。
def int2bin(val):
res=''
while val>0:
res += str(val&1)
val=val>>1 # val=val/2
return res[::-1] # reverse the string
不反转字符串的更快版本。
def int2bin(val):
res=''
while val>0:
res = chr((val&1) + 0x30) + res
val=val>>1
return res
下面是我刚刚实现的代码。这不是一个方法,但你可以把它作为一个现成的函数使用!
def inttobinary(number):
if number == 0:
return str(0)
result =""
while (number != 0):
remainder = number%2
number = number/2
result += str(remainder)
return result[::-1] # to invert the string
使用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)
如果你正在寻找与hex()等价的bin(),它是在python 2.6中添加的。
例子:
>>> bin(10)
'0b1010'
下面是一个使用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