CKTIS / JavaScript
DataView.prototype.getUint16(): read an unsigned 16-bit integer
Read two bytes from a DataView as an unsigned 16-bit integer, choosing the byte order specified by the data format.
Version: ECMAScript 2024 and the current web platform; runtime support varies
Syntax
view.getUint16(byteOffset)
view.getUint16(byteOffset, littleEndian)DataView.prototype.getUint16 is an instance method on DataView. It reads two consecutive bytes without modifying the buffer and returns a Number from 0 through 65535, inclusive. Use getInt16() if the field is signed.
byteOffset counts bytes from the start of the view, not from the start of the buffer or in 16-bit units. There is no alignment requirement: an odd offset is valid if both bytes fit inside the view.
The optional littleEndian argument is converted to a Boolean. true selects little-endian (least significant byte first); false or omission selects big-endian (most significant byte first). Choose the byte order from the data format, not the processor architecture.
The offset is converted to an integer index: undefined becomes 0, and fractions are truncated toward zero. A negative result of that conversion throws RangeError, as does a read whose two bytes do not fit inside a valid view. A TypeError occurs, for example, if this is not a DataView instance, the buffer is detached, or the view itself is out of bounds after the buffer shrinks.
Examples
const bytes = new Uint8Array([0xaa, 0xbb, 0x12, 0x34, 0xcc]);
const view = new DataView(bytes.buffer, 1, 3);
console.log(view.getUint16(1));
console.log(view.getUint16(1, true));
try {
view.getUint16(2);
} catch (error) {
console.log(error.name);
}Result
4660 13330 RangeError
The view starts at buffer index `1`, so view offset `1` selects `0x12` and `0x34`. The default read returns `4660`, and the read with `true` returns `13330`. At offset `2`, only one byte remains in the view, so the code logs `RangeError`.
Related lessons
- JavaScript · Lesson 2 · Advanced · Version: 4