浮点数(base-10)到 IEEE-754 32 位转换器的结果是错误的

Floating point number (base-10) to IEEE-754 32 bits converter's result is wrong

我的浮点数(base-10)到 IEEE-754 32 位转换器的答案是错误的,我不太确定是什么原因。这是我的代码,请原谅我混淆的变量名。我是编码新手。 我从这个网站得到了这个解决方案。 https://www.wikihow.com/Convert-a-Number-from-Decimal-to-IEEE-754-Floating-Point-Representation

它应该是的结果:

0100001001101010010000000000000

我得到的结果:

0100001001011110010000000000000

x = str(58.5625)
s = x.split(".")

a = int(s[0])
p = int(s[1])
q = "0." + str(p)
b = float(q)

front = ""
end = ""

while a > 0:
    front += str(a % 2)
    a //= 2
    a = int(a)

while b != 1 and len(end) < 17:
    b *= 2
    end += str(b)[0]
    b -= int(str(b)[0])

print(a, b)
print(front, end)

whole = front + "." + end

count = whole.find('.') - 1

ff = whole.split('.')
q1 = ff[0]
q2 = ff[1]

c = (q1 + q2)[1:]
te = float(x)
if te > 0:
    signofnum = '0'
else :
    signofnum = '1'

expobased = count + 127

exponent = ""

while expobased > 0:
    exponent += str(expobased % 2)
    expobased //= 2
    expobased = int(expobased)

exponent = exponent[::-1]

mantissa = c

result = signofnum + exponent + mantissa
print(result)

你的 front 倒退了。循环从右到左获取位(首先是 lowest/rightmost 位,最后是 greatest/leftmost 位)并将它们附加到 front 上,因此最低位首先出现,然后是第二低位bit 被附加在它的右边,依此类推,直到输入的最高位被放在 front 的最右边。修复问题中样本值的正确结果。可以通过将 front += str(a % 2) 更改为 front = str(a % 2) + front

来修复

此外,请勿使用:

s = x.split(".")
…
p = int(s[1])

小数部分不是整数,将其转换为整数会丢失有关其位置的信息(前导零)。要得到 b,小数部分,只需从原始数字中减去 a(整数部分)。获得 a 可能也是更可取的 int(<i>number</i>);根本不需要转换成字符串。