setUint16() writes an unsigned 16-bit whole number (0 to 65535) into two bytes of a DataView. Give it the byte offset, the value and, if needed, true for little-endian order. It is what you reach for when you build a binary message with a 2-byte length, port or ID field. Values outside the range wrap around modulo 65536.
Converts value to a unsigned 16-bit integer (0 to 65535) and writes it into the 2 bytes starting at byteOffset, big-endian. Returns undefined.
view.setUint16(byteOffset, value, true)
Writes the same 2 bytes in little-endian order, so the least significant byte lands at byteOffset.
Part of the original DataView from ES2015, so every modern browser and runtime has it. Unlike a Uint16Array, a DataView has no alignment rule: setUint16() works at any byte position, even one that is not a multiple of 2.
Library declarations
JavaScript
DataView.prototype.setUint16(byteOffset, value)
DataView.prototype.setUint16(byteOffset, value, littleEndian)
// returns undefined; writes 2 bytes starting at byteOffset
// value is converted to a unsigned 16-bit integer
// needs byteOffset + 2 <= view.byteLength, else RangeError
// littleEndian: false or left out = big-endian
Parameters
Parameter
Description
byteOffset
Where to start writing, counted in bytes from the start of the view (not of the underlying buffer). It is converted to a whole number, so 1.9 means 1 and "2" means 2. All 2 bytes must fit: byteOffset + 2 may not be larger than view.byteLength. A negative or too-large offset throws a RangeError.
value
The number to store. It is converted to a Number, the fraction is cut off (3.9 becomes 3, -3.9 becomes -3), and the result wraps around modulo 65536 into 0 to 65535. NaN and Infinity are stored as 0.
littleEndian
Optional. Leave it out (or pass false) for big-endian: the most significant of the 2 bytes comes first. Pass true for little-endian: the least significant byte comes first. Any truthy value, such as 1, also means little-endian.
Return Value
Return Value
Description
undefined
setUint16() gives nothing back. Its result is the 2 bytes it changed inside the buffer; read them back with getUint16().
JavaScript Examples
Example 1 — Build a Packet With a 2-Byte Length Field
Put the length of a short text in the first two bytes of a packet, followed by the text itself.
JavaScript
const payload = new TextEncoder().encode("Hi!");
const packet = new Uint8Array(2 + payload.length);
const view = new DataView(packet.buffer);
view.setUint16(0, payload.length); // length first
packet.set(payload, 2); // then the text
const hex = Array.from(packet, function (b) { return b.toString(16).padStart(2, "0"); }).join(" ");
console.log(hex); // 00 03 48 69 21