ArrayBuffer, Uint8Array, Uint16Array, DataView.prototype.getUint16
new ArrayBuffer(length)
buffer.byteLength
new Uint8Array(buffer)
new Uint16Array(buffer)
new DataView(buffer)
view.getUint16(byteOffset, littleEndian)Create a buffer, view it as 8-bit or 16-bit elements, and read multi-byte values with an explicit endianness.
| Parameter | Description |
|---|---|
length | The size of the ArrayBuffer in bytes. |
buffer | The ArrayBuffer backing the view. Multiple views may share it. |
byteOffset, littleEndian | getUint16 reads two bytes at byteOffset. littleEndian true is little-endian; false is big-endian. |
Returns: byteLength is a number of bytes. A typed array length is a number of elements, not bytes. getUint16 returns an unsigned 16-bit number.
- This host is little-endian: u16[0] === view.getUint16(0, true). The example prints both DataView orders so the result does not depend on guessing the platform.
const buffer = new ArrayBuffer(8);
const bytes = new Uint8Array(buffer);
const words = new Uint16Array(buffer);
console.log(buffer.byteLength, bytes.length, words.length);
bytes[0] = 0x11;
bytes[1] = 0x22;
bytes[2] = 0x33;
bytes[3] = 0x44;
console.log(JSON.stringify(Array.from(bytes)));
const view = new DataView(buffer);
console.log(view.getUint16(0, true), view.getUint16(2, true));
console.log(view.getUint16(0, false), view.getUint16(2, false));
console.log(view.getUint16(0, true) === words[0]);Expected output
8 8 4
[17,34,51,68,0,0,0,0]
8721 17459
4386 13124
true