Python 2.7 将十进制转换为二进制的Python代码

Python 2.7 将十进制转换为二进制的Python代码,python-2.7,binary,Python 2.7,Binary,我需要编写一个Python脚本,将以10为基数的x和数字转换为小数点后最多有n个值的二进制。我不能只使用bin(x)!以下是我所拥有的: def decimal_to_binary(x, n): x = float(x) test_str = str(x) dec_at = test_str.find('.') #This section will work with numbers in front of the decimal p=0 bin

我需要编写一个Python脚本,将以10为基数的x和数字转换为小数点后最多有n个值的二进制。我不能只使用bin(x)!以下是我所拥有的:

def decimal_to_binary(x, n):
    x = float(x)
    test_str = str(x)
    dec_at = test_str.find('.')

    #This section will work with numbers in front of the decimal
    p=0
    binary_equivalent = [0]
    c=0
    for m in range(0,100):
        if 2**m <= int(test_str[0:dec_at]):
            c += 1
        else:
            break

    for i in range(c, -1, -1):
        if 2**i + p <= (int(test_str[0:dec_at])):
            binary_equivalent.append(1)
            p = p + 2**i
        else:
            binary_equivalent.append(0)
    binary_equivalent.append('.')

    #This section will work with numbers after the decimal
    q=0
    for j in range(-1, -n-1, -1):
        if 2**j + q <= (int(test_str[dec_at+1:])):
            binary_equivalent.append(1)
            q = q + 2**j
        else:
            binary_equivalent.append(0)

    print float((''.join(map(str, binary_equivalent))))
def十进制到二进制(x,n):
x=浮动(x)
test_str=str(x)
dec_at=测试str.find('.'))
#本节将处理小数点前面的数字
p=0
二进制_等价物=[0]
c=0
对于范围(0100)内的m:

如果2**m你很接近,但是当你超过小数点时,你的比较有问题:

if 2**j + q <= (int(test_str[dec_at+1:])):
代码中的实际比较是:

0.5 <= 4

0.5您很接近,但是当您超出小数点时,您的比较会出现问题:

if 2**j + q <= (int(test_str[dec_at+1:])):
代码中的实际比较是:

0.5 <= 4

0.5哦,好悲伤。这是一个很简单的错误…非常感谢!哦,好悲伤。这是一个很简单的错误…非常感谢!