在Python中有任何罐装的Python方法将整数(或长)转换为二进制字符串吗?
谷歌上有无数的dec2bin()函数…但我希望我可以使用内置函数/库。
在Python中有任何罐装的Python方法将整数(或长)转换为二进制字符串吗?
谷歌上有无数的dec2bin()函数…但我希望我可以使用内置函数/库。
当前回答
计算器与DEC,BIN,HEX的所有必要功能: (使用Python 3.5制作和测试)
您可以更改输入的测试数字并获得转换后的数字。
# CONVERTER: DEC / BIN / HEX
def dec2bin(d):
# dec -> bin
b = bin(d)
return b
def dec2hex(d):
# dec -> hex
h = hex(d)
return h
def bin2dec(b):
# bin -> dec
bin_numb="{0:b}".format(b)
d = eval(bin_numb)
return d,bin_numb
def bin2hex(b):
# bin -> hex
h = hex(b)
return h
def hex2dec(h):
# hex -> dec
d = int(h)
return d
def hex2bin(h):
# hex -> bin
b = bin(h)
return b
## TESTING NUMBERS
numb_dec = 99
numb_bin = 0b0111
numb_hex = 0xFF
## CALCULATIONS
res_dec2bin = dec2bin(numb_dec)
res_dec2hex = dec2hex(numb_dec)
res_bin2dec,bin_numb = bin2dec(numb_bin)
res_bin2hex = bin2hex(numb_bin)
res_hex2dec = hex2dec(numb_hex)
res_hex2bin = hex2bin(numb_hex)
## PRINTING
print('------- DECIMAL to BIN / HEX -------\n')
print('decimal:',numb_dec,'\nbin: ',res_dec2bin,'\nhex: ',res_dec2hex,'\n')
print('------- BINARY to DEC / HEX -------\n')
print('binary: ',bin_numb,'\ndec: ',numb_bin,'\nhex: ',res_bin2hex,'\n')
print('----- HEXADECIMAL to BIN / HEX -----\n')
print('hexadec:',hex(numb_hex),'\nbin: ',res_hex2bin,'\ndec: ',res_hex2dec,'\n')
其他回答
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")
与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将是表示转换失败的哨兵值。(这是假设您只转换正数,无论它们是整数还是长数)。
我很惊讶,没有提到一个很好的方法来实现这一点,使用Python 3.6及更高版本支持的格式化字符串。TLDR:
>>> number = 1
>>> f'0b{number:08b}'
'0b00000001'
长故事
这是Python 3.6提供的格式化字符串的功能:
>>> x, y, z = 1, 2, 3
>>> f'{x} {y} {2*z}'
'1 2 6'
你也可以请求二进制文件:
>>> f'{z:b}'
'11'
指定宽度:
>>> f'{z:8b}'
' 11'
请求零填充:
f'{z:08b}'
'00000011'
并添加公共前缀表示二进制数:
>>> f'0b{z:08b}'
'0b00000011'
你也可以让Python为你添加前缀,但我不喜欢上面的版本,因为你必须把前缀考虑到宽度:
>>> f'{z:#010b}'
'0b00000011'
更多信息可在格式化字符串文字和格式规范迷你语言的官方文档中获得。
这是针对python3的,它保持前导0 !
print(format(0, '08b'))
n=input()
print(bin(n).replace("0b", ""))