Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript float from/to bits

I am trying to perform something that is brain-dead simple in any other language but not javascript: get the bits out of float (and the other way around).

In C/C++ it would be something like

 float a = 3.1415; int b = *((int*)&a); 

and vise-versa

 int a = 1000; float b = *((float*)&a); 

In C# you can use the BitConverter ...floatBits or something alike in Java... Even in VB6 for Christ's sake you can memcpy a float32 into an int32. How on earth can I translate between and int and a float in javascript?

like image 482
Stelios Avatar asked Jan 05 '10 01:01

Stelios


People also ask

Is Float data type in JavaScript?

JavaScript Number Data types JavaScript has only one Number (numeric) data types. Number data type can store normal integer, floating-point values. A floating-point represent a decimal integer with either decimal points or fraction expressed (refer to another decimal number).

How many bits are JavaScript numbers?

The JavaScript Number type is a double-precision 64-bit binary format IEEE 754 value, like double in Java or C#.

Is there int in js?

"There's no such thing as an integer in JavaScript, so you have to be a little careful with your arithmetic if you're used to math in C or Java."


1 Answers

function DoubleToIEEE(f) {     var buf = new ArrayBuffer(8);     (new Float64Array(buf))[0] = f;     return [ (new Uint32Array(buf))[0] ,(new Uint32Array(buf))[1] ]; } 
like image 64
passing korean Avatar answered Oct 12 '22 02:10

passing korean