skip to Main Content

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


  1. 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 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));
    Login or Signup to reply.
  2. Two issues:

    • The indices you pass to data view methods are byte offsets in the buffer, whereas the indices on data target Uint16Array elements each of which is two bytes.
    • An Uint16Array has an endianess that you need to consider when accessing individual bytes. With the DataView, you can explicitly choose whether to use little endian or big endian. If you want to access the values of an Uint16Array using a DataView, 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.
    const data = new Uint16Array([7, 12, 100]);
    const view = new DataView(data.buffer);
    
    // not everyone will get the same output!
    console.log(view.getUint16(0, false), view.getUint16(2, false), view.getUint16(4, false));
    console.log(view.getUint16(0, true), view.getUint16(2, true), view.getUint16(4, true));
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search