将两个Uint32Array值转换为Javascript编号

时间:2014-01-22 10:35:17

标签: javascript types numbers

我找到了here的代码,它将Javascript编号转换为内部IEEE表示形式为两个Uint32值:

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

如何将返回值转换回Javascript号码?这样:

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

2 个答案:

答案 0 :(得分:3)

我找到了一个可行的解决方案,似乎有效:

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];
}

用法:

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

答案 1 :(得分:3)

那段代码很丑陋。使用

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

如果您想要实际的Array而不是Uint32Array(在大多数情况下不应该有所作为),请添加Array.from来电。您还可以通过将值传递给Float64Array构造函数来将其减少为oneliner:

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));
}

反向只会将输入写入uint个插槽并返回float[0]值:

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];
}

可以缩短为

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