在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')
其他回答
由于前面的答案大多使用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。
计算二进制数:
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
下面是使用divmod()函数的简单解决方案,该函数返回提示符和除法的结果,但不包含分数。
def dectobin(number):
bin = ''
while (number >= 1):
number, rem = divmod(number, 2)
bin = bin + str(rem)
return bin
与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实际上已经为此内置了一些东西,能够执行诸如'{0:b}'.format(42)之类的操作,这将为您提供42或101010的位模式(在字符串中)。
从更普遍的理念来看,没有一种语言或库能够满足用户的所有需求。如果您所工作的环境不能提供您所需要的内容,那么您应该在开发时收集代码片段,以确保您永远不必编写相同的内容两次。例如,伪代码:
define intToBinString, receiving intVal:
if intVal is equal to zero:
return "0"
set strVal to ""
while intVal is greater than zero:
if intVal is odd:
prefix "1" to strVal
else:
prefix "0" to strVal
divide intVal by two, rounding down
return strVal
它将根据十进制值构造二进制字符串。请记住,这是一个通用的伪代码,它可能不是最有效的方法,尽管你似乎提出了迭代,它不会有太大的区别。它实际上只是一个指导方针,告诉你如何去做。
一般思想是使用以下代码(按优先级排序):
语言或内置库。 具有合适许可证的第三方库。 你自己的收藏。 你需要写一些新的东西(并保存在你自己的收藏中以备以后使用)。