How to properly access the elements in data views based on the data type?
Consider the following example code:
const data = new Uint16Array([7, 12, 100]);
const view = new DataView(data.buffer);
console.log(view.getUint16(0), view.getUint16(1), view.getUint16(3));
The output is 1792 12 100
. The first element is wrong, and the other element offsets are not multiples of 2 as 16 bit types would suggest. Using view.getUint8(0)
does output 7
.
What is the correct way to access elements in a data view using .getTYPE()
?
The real use-case is a binary file that is read in as an ArrayBuffer
of mixed sized values.
You are using the wrong offsets in the getUint16
calls. The offset is in bytes, and thus is based on the data type, in this case 16. As 16 bits is 2 bytes the offset should be in increments of 2.
Note that there is a second argument to the getTYPE
methods, which specifies the byte ordering, whether big- or little-endian. Most of the time you will want to use little-endian, which requires you pass true
as the second argument.
const data = new Uint16Array([7, 12, 100]);
const view = new DataView(data.buffer);
console.log(view.getUint16(0, true));
console.log(view.getUint16(2, true));
console.log(view.getUint16(4, true));