Skip to content

Latest commit

 

History

History

float32-from-binary-string

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 
 
 
 
 
 
 
 
 

From Binary String

Create a single-precision floating-point number from an IEEE 754 literal bit representation.

Usage

var fromBits = require( '@stdlib/math/base/utils/float32-from-bits' );

fromBits( bstr )

Creates a single-precision floating-point number from an IEEE 754 literal bit representation.

var bstr = '01000000100000000000000000000000';
var val = fromBits( bstr );
// returns 4

bstr = '01000000010010010000111111011011';
val = fromBits( bstr );
// returns ~3.14

bstr = '11111111011011000011101000110011';
val = fromBits( bstr );
// returns ~-3.14e+38

The function handles subnormals.

bstr = '10000000000000000000000000010110';
val = fromBits( bstr );
// returns ~-3.08e-44

bstr = '00000000000000000000000000000001';
val = fromBits( bstr );
// returns ~1.40e-45

The function handles special values.

bstr = '00000000000000000000000000000000';
val = fromBits( bstr );
// returns 0

bstr = '10000000000000000000000000000000';
val = fromBits( bstr );
// returns -0

bstr = '01111111110000000000000000000000';
val = fromBits( bstr );
// returns NaN

bstr = '01111111100000000000000000000000';
val = fromBits( bstr );
// returns +infinity

bstr = '11111111100000000000000000000000';
val = fromBits( bstr );
// returns -infinity

Examples

var round = require( '@stdlib/math/base/special/round' );
var pow = require( '@stdlib/math/base/special/pow' );
var toFloat32 = require( '@stdlib/math/base/utils/float64-to-float32' );
var toBits = require( '@stdlib/math/base/utils/float32-to-binary-string' );
var fromBits = require( '@stdlib/math/base/utils/float32-from-binary-string' );

var frac;
var sign;
var exp;
var b;
var x;
var y;
var i;

// Convert random numbers to IEEE 754 literal bit representations and then convert them back...
for ( i = 0; i < 100; i++ ) {
	if ( Math.random() < 0.5 ) {
		sign = -1;
	} else {
		sign = 1;
	}
	frac = Math.random() * 10;
	exp = round( Math.random()*100 );
	if ( Math.random() < 0.5 ) {
		exp = -exp;
	}
	x = sign * frac * pow( 2, exp );
	x = toFloat32( x );

	b = toBits( x );
	y = fromBits( b );

	console.log( '%d => %s => %d', x, b, y );
	console.log( x === y );
}