Convert uint8array to double in javascript

微笑、不失礼 提交于 2021-02-10 07:46:28

问题


I have an arraybuffer and I want to get double values.For example from [64, -124, 12, 0, 0, 0, 0, 0] I would get 641.5

Any ideas?


回答1:


You could adapt the excellent answer of T.J. Crowder and use DataView#setUint8 for the given bytes.

var data =  [64, -124, 12, 0, 0, 0, 0, 0];

// Create a buffer
var buf = new ArrayBuffer(8);
// Create a data view of it
var view = new DataView(buf);

// set bytes
data.forEach(function (b, i) {
    view.setUint8(i, b);
});

// Read the bits as a float/native 64-bit double
var num = view.getFloat64(0);
// Done
console.log(num);

For multiple numbers, you could take chunks of 8.

function getFloat(array) {
    var view = new DataView(new ArrayBuffer(8));
    array.forEach(function (b, i) {
        view.setUint8(i, b);
    });
    return view.getFloat64(0);
}

var data =  [64, -124, 12, 0, 0, 0, 0, 0, 64, -124, 12, 0, 0, 0, 0, 0],
    i = 0,
    result = [];

while (i < data.length) {
    result.push(getFloat(data.slice(i, i + 8)));
    i += 8;
}

console.log(result);



回答2:


Based on the answer from Nina Scholz I came up with a shorter:

function getFloat(data /* Uint8Array */) {
  return new DataView(data.buffer).getFloat64(0);
}

Or if you have a large array and know the offset:

function getFloat(data, offset = 0) {
  return new DataView(data.buffer, offset, 8).getFloat64(0);
}


来源:https://stackoverflow.com/questions/46153073/convert-uint8array-to-double-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!