Michael Lamontagne
Michael Lamontagne

Reputation: 43

Trouble with my code for IEEE-754 representation of any double-precision floating-point value

I am working on code that should take a floating point value and convert it into the following tuple format:

(+ or - sign, significand a string of 54 bits, exponent).

For one of my tests v = 6.2831853072, I am getting a slightly wrong answer but this code is passing all other tests. I should also note that I am new to python so my code is not the most efficient.

What I should be getting as a correct response: ('+', '1.1001001000011111101101010100010001001000011011100000', 2)

What I am actually generating which is wrong:

('+', '1.0000001000011111101101010100010001001000011011100000', 2)

Any perspective would be appreciated. Of course any code optimization recommendations is welcomed too.

Code:

v = 6.2831853072
vhex = v.hex()
# print(v.hex())

if v == 0.0:
    s_sign = '+'
    v_exp = 0
    fp = '0.0000000000000000000000000000000000000000000000000000'

elif str(vhex[0]) == '-':

    s_sign = '-'
    signand = vhex.split('p')
    signand = signand[0][3:]
#     print(signand[2:])

    v_exp = vhex.split('p')
    v_exp = int((v_exp[1]))

    integer = int(signand[2:], 16)
    fp = format(integer, '0>52b')
    fp = vhex[3:5] + fp
    
else:
    s_sign = '+'

    signand = vhex.split('p')
    signand = signand[0][3:]

    print(signand[0][3:])
    v_exp = vhex.split('p')
    v_exp = int((v_exp[1]))

    integer = int(signand[2:], 16)
    fp = format(integer, '0>52b')
    fp = vhex[2:4] + fp

print(integer)
print(vhex)
tt = (s_sign, fp,v_exp)
tt

Upvotes: 0

Views: 2299

Answers (1)

shilpa gopi
shilpa gopi

Reputation: 23

I could see that issue is when the number is positive

integer = int(signand[2:], 16)

The index range [2:0] will vomit the first digit, it must be signand[1:0]

Here is the implementation without using the index range, this can handle 0.0 as well

def floating_point_bin(v):
    vhex = v.hex()
    vhex_parts = vhex.split('0x')

    signand, v_exp = vhex_parts[-1].split('p')
    sign, precision = signand.split('.')

    signand_int = int(precision, 16)
    fp = format(signand_int, '0>52b')

    s_signif = sign +'.'+ fp
    v_exp = int(v_exp)
    if vhex_parts[0] == '':
        s_sign = '+'
    else:
        s_sign = '-'    
    return s_sign, s_signif, v_exp

Upvotes: 1

Related Questions