Skip to content

Instantly share code, notes, and snippets.

@omkarkhair
Last active October 8, 2015 09:47
Show Gist options
  • Save omkarkhair/3313932 to your computer and use it in GitHub Desktop.
Save omkarkhair/3313932 to your computer and use it in GitHub Desktop.
Hex string to Float (32bit) IEEE 754
<html>
<head>
<script>
/*
Converts a 32bit HEX string (42883EFA) to Float 68.1229476928711
Complies to IEEE 754 Standards.
Tested with a range of sample inputs. Feel free to report a bug.
*/
function HexStr2Dec(str) // Converts the string into an actual array of 4bit decimal values (Hex values)
{
var res = [];
str = str.toUpperCase();
var len = str.length;
for(var i = 0; i < len; i++)
{
var chc = str[i].charCodeAt(0);
if( chc >= 48 && chc <= 57 )
{
res.push(chc - 48);
}
else if( chc >= 65 && chc <= 70 )
{
res.push(chc - 55);
}
}
return res;
}
function Byte2Float(num) //4 byte float input conversion
{
var sign = ((num[0] >> 4) & 8)/8;
var exp = ((((num[0] * 256) + num[1]) & 0x7F80 ) >> 7) - 127;
var significand = ((num[1] * 65536 + num[2] * 256 + num[3]) & 8388607).toString(2);
var frac = 1;
var max = 23;
for(var i = (significand.length-1); i >= 0; i--)
{
frac += (significand[i] / Math.pow(2,max));
max--;
}
var res = Math.pow(-1,sign) * frac * Math.pow(2,exp);
return res;
}
function Binary2Float(num) //Takes an 4 bit Integer array (length of 8), which read as binary for bit wise calculations.
{
var sign = (num[0] & 8)/8;
var exp = (((num[0] * 256 + num[1] * 16 + num[2]) & 2040) >> 3) - 127;
var significand = ((num[2] * 1048576 + num[3] * 65536 + num[4] * 4096 + num[5] * 256 + num[6] * 16 + num[7]) & 8388607).toString(2);
var frac = 1;
var max = 23;
for(var i = (significand.length-1); i >= 0; i--)
{
frac += (significand[i] / Math.pow(2,max));
max--;
}
var res = Math.pow(-1,sign) * frac * Math.pow(2,exp);
return res;
}
function calc()
{
var str = document.getElementById("txtInput").value;
document.getElementById("result").innerHTML = Binary2Float(HexStr2Dec(str));
}
</script>
</head>
<body onload="">
<input type="text" id="txtInput">
<input type="button" value="calculate" onclick="calc()">
<div id="result"></div>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment