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.
2
Answers
You are using the wrong offsets in the
getUint16
calls. The offset is based on the data type, in this case 16. 16 bits is 2 bytes, so the offset for each 16 bit integer 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 passtrue
as the second argument.Two issues:
data
targetUint16Array
elements each of which is two bytes.Uint16Array
has an endianess that you need to consider when accessing individual bytes. With theDataView
, you can explicitly choose whether to use little endian or big endian. If you want to access the values of anUint16Array
using aDataView
, you have to use the system endianness; if you want to read from a binary file you have to check the file format specification that will tell you which endianness to use.