在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')
其他回答
这是我的答案,它工作得很好…!
def binary(value) :
binary_value = ''
while value !=1 :
binary_value += str(value%2)
value = value//2
return '1'+binary_value[::-1]
这是另一种算法的解决方案,使用位运算符。
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
这是针对python3的,它保持前导0 !
print(format(0, '08b'))
>>> format(123, 'b')
'1111011'
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
它将根据十进制值构造二进制字符串。请记住,这是一个通用的伪代码,它可能不是最有效的方法,尽管你似乎提出了迭代,它不会有太大的区别。它实际上只是一个指导方针,告诉你如何去做。
一般思想是使用以下代码(按优先级排序):
语言或内置库。 具有合适许可证的第三方库。 你自己的收藏。 你需要写一些新的东西(并保存在你自己的收藏中以备以后使用)。