setInt16() writes a signed 16-bit whole number (-32768 to 32767) into two bytes of a DataView. You pass the byte offset, the value, and optionally true for little-endian order. Big-endian, the default, writes the high byte first; little-endian writes the low byte first. Numbers outside the range wrap around, so 40000 is stored as -25536.
Converts value to a signed 16-bit integer (-32768 to 32767) and writes it into the 2 bytes starting at byteOffset, big-endian. Returns undefined.
view.setInt16(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 Int16Array, a DataView has no alignment rule: setInt16() works at any byte position, even one that is not a multiple of 2.
Library declarations
JavaScript
DataView.prototype.setInt16(byteOffset, value)
DataView.prototype.setInt16(byteOffset, value, littleEndian)
// returns undefined; writes 2 bytes starting at byteOffset
// value is converted to a signed 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 -32768 to 32767. 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
setInt16() gives nothing back. Its result is the 2 bytes it changed inside the buffer; read them back with getInt16().
JavaScript Examples
Example 1 — Write Audio Samples in Little-Endian Order
Write four 16-bit audio samples the way a WAV file stores them, then look at the bytes.