Timo Kähkönen
Timo Kähkönen

Reputation: 12210

Converting two Uint32Array values to Javascript number

I found a code from here that converts Javascript number to inner IEEE representation as two Uint32 values:

function DoubleToIEEE(f)
{
  var buf = new ArrayBuffer(8);
  (new Float64Array(buf))[0] = f;
  return [ (new Uint32Array(buf))[0] ,(new Uint32Array(buf))[1] ];
}

How to convert the returned value back to Javascript number? This way:

var number = -10.3245535;
var ieee = DoubleToIEEE(number)
var number_again = IEEEtoDouble(ieee);
// number and number_again should be the same (if ever possible)

Upvotes: 7

Views: 5064

Answers (2)

Bergi
Bergi

Reputation: 664579

That code is ugly as hell. Use

function DoubleToIEEE(f) {
  var buf = new ArrayBuffer(8);
  var float = new Float64Array(buf);
  var uint = new Uint32Array(buf);
  float[0] = f;
  return uint;
}

If you want an actual Array instead of a Uint32Array (shouldn't make a difference in the most cases), add an Array.from call. You can also reduce this to a oneliner by passing the value to the Float64Array constructor:

function DoubleToIEEE(f) {
  // use either
  return new Uint32Array(Float64Array.of(f).buffer);
  return Array.from(new Uint32Array(Float64Array.of(f).buffer));
  return Array.from(new Uint32Array((new Float64Array([f])).buffer));
}

The inverse would just write the inputs into the uint slots and return the float[0] value:

function IEEEToDouble(is) {
  var buf = new ArrayBuffer(8);
  var float = new Float64Array(buf);
  var uint = new Uint32Array(buf);
  uint[0] = is[0];
  uint[1] = is[1];
  return float[0];
}

which can be shortened to

function IEEEToDouble(is) {
  return (new Float64Array(Uint32Array.from(is).buffer))[0];
}

Upvotes: 7

Timo Kähkönen
Timo Kähkönen

Reputation: 12210

I found a possible solution, which seems to work:

function IEEEToDouble(f)
{
  var buffer = new ArrayBuffer(8);
  (new Uint32Array(buffer))[0] = f[0];
  (new Uint32Array(buffer))[1] = f[1];
  return new Float64Array(buffer)[0];
}

Usage:

var a = DoubleToIEEE(-0.1234);
console.log(a); // [0, 3220176896]
var b = IEEEToDouble(a);
console.log(b); // -0.1234

Upvotes: 8

Related Questions