Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hex decimal to float Python

I'm reading data from a binary file. I have a document that lets me know how the information is stored. To be sure of this I use XVI32.

I was extracting information string and int data correctly, until I bumped with float data type.

According to this file:

00800000 = 0.0
7AFBDD35 = 0.061087
9BF7783C = -0.003491
00FBFCAD = 0.031416

I tried to solve this with:

struct.unpack('!f', my_float.decode('hex'))[0]

And other different ways....

I tested this information with some online tools like: http://babbage.cs.qc.cuny.edu/IEEE-754/index.xhtml and http://www.binaryconvert.com/result_float.html?decimal=048046048054049048056055, but all of these ways throws me a different value according the original results.

I'm starting to suspect that float information is encrypted or something like that but why string and int weren't encrypted?

like image 633
Hugo Medina Avatar asked May 12 '26 03:05

Hugo Medina


2 Answers

Interesting puzzle. Working with the documentation I came up with this:

def byteswap(x):
    return ((x & 0x00ff00ff) << 8) | ((x & 0xff00ff00) >> 8)


def tms320_float(raw):
    s = (raw >> 23) & 1
    mantissa = (raw & 0x007fffff)
    exponent = raw >> 24
    if exponent >= 128:
        exponent -= 256
    if exponent == -128:
        return 0.0
    return (((-2) ** s) + float(mantissa) / float(1 << 23)) * (2.0 ** exponent)

>>> tms320_float(byteswap(0x00800000))
0.0
>>> tms320_float(byteswap(0x7AFBDD35))
0.06108652427792549
>>> tms320_float(byteswap(0x9BF7783C))
-0.003490658476948738
>>> tms320_float(byteswap(0x00FBFCAD))
0.031415924429893494
like image 106
Mark Ransom Avatar answered May 14 '26 17:05

Mark Ransom


my boss sent me the answer, The floating point data is not in IEEE format.

The data type is TMS320 floating point

for some reason, the real values from hex data are mixed each 2 bytes, I mean:

80000000 = 0.0
FB7A35DD = 0.061087
F79B3C78 = -0.003491
FB00ADFC = 0.031416

Thankyou for support me guys

like image 26
Hugo Medina Avatar answered May 14 '26 17:05

Hugo Medina