# Hex to float

Hello, I am trying to convert hex (“0x41B9DDDE”) into a floating point which happens to be temperature (“23.233334”).

I tried the code
`local hexString = "41B9DDDE"; hexString = "0x" + hexString; local hexFloat = hexString.tofloat();`

When I did
`server.log(hexString); server.log(format("%0.4f",hexFloat)); server.log(hexFloat);`

and the result I got was
`0x41B9DDDE 0.0000 0`

Hmm. According to this calculator I should be expecting “23.233334”.

I can try to look up for the formula behind it then process it manually and post it over here once I got it working.

The command for it in Python is something like
`struct.unpack('!f', '\\x41\\xb9\\xdd\\xde')`

The way of doing it is convert the hex to binary which is 0100 0001 1011 1001 1101 1101 1101 1110.

First bit = Sign bit
Next 8 bit = exponent with an offset of 127
Remainder = mantissa

Floating point = sign bit * 2^exponent * mantissa

For “0x41B9DDDE”

Sign bit = 0 ( positive ) = +1
Exponent = 10010011 - 127 = 131 - 127 = 4
Mantissa = 1 + (011 1001 1101 1101 1101 1110) = 1 + 0*(1/2) + 1*(1/4) + 1*(1/8) + 1*(1/16) + 0*(1/32) + 0*(1/64) + 1*(1/128) + 1*(1/256) + 1*(1/512) … = 1.452

Floating point = +1 * 2^4 * 1.452 = 23.232

Formula is referenced from here.

Is there a way to convert the hex to binary in a blob format for further calculations?

Convert the hex to bytes, write to a blob, rewind the blob, and then read it as a float?

The blob technique would work, but Squirrel does offer a shortcut:

```````local hexString = "41B9DDDE";
hexString = "0x" + hexString;
local hexFloat = casti2f(hexString.tointeger());
server.log(typeof(hexFloat) + ": " + hexFloat);
`
``````

Peter

That worked for me. Thank you.

`casti2f(integer);`

is the code I’m looking for.

That’s my code which worked for me.

`local prime_temp = casti2f(frame[97]*16777216 + frame[98]*65535 + frame[99]*256 + frame[100]);`

What datatype is “frame”? If it’s a blob, you can go

```````frame.seek(97, 'b');
```````frame.seek(97, 'b');