Jones
Jones

Reputation: 3

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

My floating point number (base-10) to IEEE-754 32 bits converter's answer is wrong and I'm not quite sure what is the reason. This is my code, please forgive me for the confusing variable names. I am new to coding. I got this solution from this website. https://www.wikihow.com/Convert-a-Number-from-Decimal-to-IEEE-754-Floating-Point-Representation

The result that it supposed to be :

0100001001101010010000000000000

The result that I got :

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)

Upvotes: 0

Views: 291

Answers (1)

Eric Postpischil
Eric Postpischil

Reputation: 222900

Your front is backwards. The loop gets the bits from right-to-left (lowest/rightmost bit first, greatest/leftmost bit last) and appends them onto front, so the lowest bit goes on first, then the second lowest bit is appended on its right, and so on until the highest bit of the input is put as the rightmost bit of front. Fixing that gets the correct result for the sample value in the question. It can be fixed by changing front += str(a % 2) to front = str(a % 2) + front

Also, do not use:

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

The fraction part is not an integer, and converting it to an integer loses information about its position (leading zeros). To get b, the fraction part, simply subtract a (the integer part) from the original number. It is probably also preferable to obtain a as int(number); there is no need to convert to a string at all.

Upvotes: 1

Related Questions