Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Correct use of getUint16()

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading