Convert uint8array to double in javascript

3k views Asked by At

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?

2

There are 2 answers

2
Nina Scholz On BEST ANSWER

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

0
floribon On

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