将两个Uint32Array值转换为Javascript编号 [英] Converting two Uint32Array values to Javascript number

查看:56
本文介绍了将两个Uint32Array值转换为Javascript编号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从此处找到了一个代码,该代码将Javascript编号转换为两个Uint32值的内部IEEE表示形式:

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

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

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)

推荐答案

该代码很难理解.使用

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 (在大多数情况下不会有所作为),请添加

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

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

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

可以缩写为

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

这篇关于将两个Uint32Array值转换为Javascript编号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆