Convert HEX value to a FLOAT value in Coldfusion

Hello,

There are several functions out there to convert HEX values to decimals and strings (thanks again @_agx_) and can be found here:

http://www.cflib.org/udf/HexToDec
http://www.cflib.org/udf/hexToString

What I need to do is convert the HEX value to a FLOAT value... I have an example using PHP:

Thank you very much in advance!!!!!!!!!!!!!!!!!!!!!!!!!
``````# Converts hexadecimal to float
function hex2float(\$hex)
{
\$sign = \$bin[0];
\$exp = bindec(substr(\$bin, 1, 8)) - 127;
\$man = (2 << 22) + bindec(substr(\$bin, 9, 23));
\$dec = \$man * pow(2, \$exp - 23) * (\$sign ? -1 : 1);
return \$dec;
}
``````
Who is Participating?

[Webinar] Streamline your web hosting managementRegister Today

x

Commented:
I'd forgotten hex to float is not as simple as it seems.   Here's a very rough version of that function that seems to work for me. But disclaimer, it's _not_ highly tested ... and I'm sure it could be improved ;-)

``````<cfscript>
function hexToFloat(hexStr)
{
var bin = right(repeatString("0", 32) & FormatBaseN(InputBaseN(hexStr, 16), 2), 32);
var sign = left(bin, 1);
var exp = "";
var man = "";
var offset = "";

if (sign == 1) {
offset = -1;
}
else {
offset = 1;
}

exp = InputBaseN(mid(bin, 2, 8), 2) - 127;
man = BitSHLN(2, 22) + InputBaseN(mid(bin, 10, 23), 2);
dec = man * (2 ^(exp - 23)) * offset;
return dec;
}
</cfscript>
``````
0

Author Commented:
I tested it against data that I know is acurate and it worked PERFECTLY!!!!!!!!!
I don't know how you figured that out but I am super impressed........ GREAT JOB!!!!!!!!!!!!!!!!!

Btw, the alogo is coming along nicely.  I'm just dynmaically "walking" down the string and looping depending on where I am / how many symbols there are etc.

Thanks again!!!!!!!!!!!!!
0

Author Commented:
SUPERB!!!!!!!!!!
0

Commented:
> Btw, the alogo is coming along nicely

Excellent! :)
0

Commented:
I just noticed I forgot to "var" scope the #dec# variable.  Here's an updated copy for PAQ purposes.

``````<cfscript>
function hexToFloat(hexStr)
{
var bin = right(repeatString("0", 32) & FormatBaseN(InputBaseN(hexStr, 16), 2), 32);
var sign = left(bin, 1);
var exp = "";
var man = "";
var offset = "";
var dec = "";

if (sign == 1) {
offset = -1;
}
else {
offset = 1;
}

exp = InputBaseN(mid(bin, 2, 8), 2) - 127;
man = BitSHLN(2, 22) + InputBaseN(mid(bin, 10, 23), 2);
dec = man * (2 ^(exp - 23)) * offset;
return dec;
}
</cfscript>
``````
0

Author Commented:
Thanks again!!!!!!!!
0

Author Commented:
One more question coming you way and then I should be finished..sorry... i need to covert HEX to LONG... I can't find any functions that would do he trick....
0