Skip to content Skip to sidebar Skip to footer

Convert Uint8array To Double In Javascript

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?

Solution 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 buffervar buf = newArrayBuffer(8);
// Create a data view of itvar view = newDataView(buf);

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

// Read the bits as a float/native 64-bit doublevar num = view.getFloat64(0);
// Doneconsole.log(num);

For multiple numbers, you could take chunks of 8.

functiongetFloat(array) {
    var view = newDataView(newArrayBuffer(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);

Solution 2:

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

functiongetFloat(data /* Uint8Array */) {
  returnnewDataView(data.buffer).getFloat64(0);
}

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

functiongetFloat(data, offset = 0) {
  returnnewDataView(data.buffer, offset, 8).getFloat64(0);
}

Post a Comment for "Convert Uint8array To Double In Javascript"