Over a million developers have joined DZone.

JavaScript Binary Single-precision Floating Point Parser

·
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)));
}
Topics:

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}