3

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?

user7597554
  • 95
  • 4
  • 11
  • show us what you've tried and what's yoyr logic? – Edwin Sep 11 '17 at 10:13
  • I have a function that returns the arraybuffer with the bytes from an audio file: function getBuffer(resolve) { var reader = new FileReader(); reader.readAsArrayBuffer(fileData); reader.onload = function () { var arrayBuffer = reader.result var bytes = new Uint8Array(arrayBuffer); resolve(bytes); } } – user7597554 Sep 11 '17 at 10:31
  • Instead of bytes from 0 to 255 I need double values – user7597554 Sep 11 '17 at 10:34

2 Answers2

5

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);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
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);
}
floribon
  • 19,175
  • 5
  • 54
  • 66