-2

我想将python中的十进制浮点数转换为二进制补码十进制二进制数。例如 1.5 二进制补码十进制 2.6(8 位)将是 0b011000。

有没有可以为我做到这一点的模块?

4

3 回答 3

1

您所描述的与十进制无关。您想将浮点数转换为定点二进制表示。为此,您可以将浮点数乘以比例因子,将其转换为整数,然后使用 Python 的内置字符串格式化工具来获取字符串表示:

def float_to_binary(float_):
    # Turns the provided floating-point number into a fixed-point
    # binary representation with 2 bits for the integer component and
    # 6 bits for the fractional component.

    temp = float_ * 2**6  # Scale the number up.
    temp = int(temp)     # Turn it into an integer.
    # If you want -1 to display as 0b11000000, include this part:
    # if temp < 0:
    #     temp += 2**8

    # The 0 means "pad the number with zeros".
    # The 8 means to pad to a width of 8 characters.
    # The b means to use binary.
    return '{:08b}'.format(temp)
于 2013-07-15T04:37:27.547 回答
0

好吧,我找不到任何东西,所以我写了一些代码并对其进行了测试。应该可以...

def floatToTwosComplementDecimal(intBits,decBits,number):
    if decBits == 0:
        mx = pow(2,intBits-1) - 1 # maximum number
    else:
        mx = pow(2,intBits-1) - pow(2,-1*decBits) # maximum number
    mn = -1*pow(2,intBits-1) # minimum number
    if number > mx:
        print "number:" + str(number) + " has been truncated to: " + str(mx)
        number = mx
    elif number < mn:
        print "number:" + str(number) + " has been truncated to: " + str(mn)
        number = mn
    n = []
    m = 0
    if number < 0:
        n.append(1)
        m = -1*pow(2,intBits-1)
    else:
        n.append(0)
        m = 0
    for i in reversed(range(intBits-1)):
        m1 = m + pow(2,i)
        if number < m1:
            n.append(0)
        else:
            n.append(1)
            m = m1
    for i in range(1,decBits+1):
        m1 = m + pow(2,-1*i)
        if number < m1:
            n.append(0)
        else:
            n.append(1)
            m = m1
    return string.join([str(i) for i in n], '')

def twosComplementDecimalToFloat(intBits,decBits,binString):
    n = 0.0
    if binString[0] == "1":
        n = -1*pow(2,intBits-1)
    for i in range(intBits-1):
        n += int(binString[intBits-1-i])*pow(2,i)
    for i in range(1,decBits+1):
        n += int(binString[intBits-1+i])*pow(2,-1*i)
    return n
于 2013-07-10T23:28:33.947 回答
0

您可以使用二进制分数包。这个包TwosComplement用二进制整数和二进制分数实现。您可以将二进制分数字符串转换为其二进制补码,反之亦然

例子:

>>> from binary_fractions import TwosComplement
>>> str(TwosComplement(-1.5)) # float --> TwosComplement
'10.1'
>>> str(TwosComplement(1.5)) # float --> TwosComplement
'01.1'
>>> TwosComplement.to_float("11111111111") # TwosComplement --> float
-1.0
>>> TwosComplement.to_float("11111111100") # TwosComplement --> float
-4.0
>>> str(TwosComplement(5)) # int --> TwosComplement
'0101'

要将其与 Binary's 而不是 float's 一起使用,您可以使用Binary同一个包中的类。

PS:无耻插件,我是这个包的作者。

于 2021-07-16T22:06:45.913 回答