Converting two Uint32Array values to Javascript number

前端 未结 2 1455
醉话见心
醉话见心 2021-01-13 03:15

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

function DoubleToIEEE(f)
{
  var buf = new ArrayB         


        
相关标签:
2条回答
  • 2021-01-13 03:49

    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
    
    0 讨论(0)
  • 2021-01-13 03:59

    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];
    }
    
    0 讨论(0)
提交回复
热议问题