在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')

其他回答

如果你正在寻找与hex()等价的bin(),它是在python 2.6中添加的。

例子:

>>> bin(10)
'0b1010'

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

它将根据十进制值构造二进制字符串。请记住,这是一个通用的伪代码,它可能不是最有效的方法,尽管你似乎提出了迭代,它不会有太大的区别。它实际上只是一个指导方针,告诉你如何去做。

一般思想是使用以下代码(按优先级排序):

语言或内置库。 具有合适许可证的第三方库。 你自己的收藏。 你需要写一些新的东西(并保存在你自己的收藏中以备以后使用)。

这是另一种算法的解决方案,使用位运算符。

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 

对于那些需要将有符号整数(范围-2**(digits-1)到2**(digits-1)-1)转换为2的补码二进制字符串的人来说,这是可行的:

def int2bin(integer, digits):
    if integer >= 0:
        return bin(integer)[2:].zfill(digits)
    else:
        return bin(2**digits + integer)[2:]

这产生:

>>> int2bin(10, 8)
'00001010'
>>> int2bin(-10, 8)
'11110110'
>>> int2bin(-128, 8)
'10000000'
>>> int2bin(127, 8)
'01111111'

下面是使用divmod()函数的简单解决方案,该函数返回提示符和除法的结果,但不包含分数。

def dectobin(number):
    bin = ''
    while (number >= 1):
        number, rem = divmod(number, 2)
        bin = bin + str(rem)
    return bin