Link to home
Start Free TrialLog in
Avatar of stracqan
stracqan

asked on

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)
    {
        $bin = str_pad(base_convert($hex, 16, 2), 32, "0", STR_PAD_LEFT);
        $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;
    }

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of _agx_
_agx_
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of stracqan
stracqan

ASKER

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!!!!!!!!!!!!!
SUPERB!!!!!!!!!!
> Btw, the alogo is coming along nicely

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


<cfscript>
    function hexToFloat(hexStr)
    {
    	// convert to binary. pad with leading zeros
    	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>

Open in new window

Thanks again!!!!!!!!
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....