DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

JavaScript Binary Single-precision Floating Point Parser

08.05.2011
| 4180 views |
  • submit to reddit
        JavaScript binary single-precision floating point parser.

Usage: bindataFloat(4-character binary string)

Coded by SiPlus on August 5, 2011.
bindataFloat = function(fInString,fBigEndian)
{
	if (fInString == null) return;
	fInString = fInString.toString();
	if (fInString.length < 4) return;
	var fBits = "";
	for (var i=0;i<4;i++)
	{
		var curByte = (fInString.charCodeAt(i)&255).toString(2);
		var byteLen = curByte.length;
		if (byteLen<8)
		{
			for (var bit=0;bit<(8-byteLen);bit++)
				curByte = '0'+curByte;
		}
		fBits = fBigEndian ? fBits+curByte : curByte+fBits;
	}
	var fSign = parseInt(fBits[0]) ? -1 : 1;
	var fExp = parseInt(fBits.substring(1,9),2)-127;
	var fMan;
	if (fExp == -127)
		fMan = 0;
	else
	{
		fMan = 1;
		for (i=0;i<23;i++)
		{
			if (parseInt(fBits[9+i])==1)
				fMan = fMan + 1/Math.pow(2,i+1);
		}
	}
	return(parseFloat((fSign*Math.pow(2,fExp)*fMan).toFixed(3)));
}