writeInt16LE() methodThe writeInt16LE() method in Node.js writes a 16-bit unsigned integer at a specified offset from a buffer in the
The writeInt16LE() method can be declared as shown in the code snippet below:
Buffer.writeInt16LE(value, offset)
value: This is a 16-bit signed integer to be written in the buffer.
offset: The offset determines the number of bytes to skip before writing to the buffer.
In other words, it is the index of the buffer.
Note: The value of
offsetshould be range from0 to (bufferLength - 2). The default value ofoffsetis0.
The writeInt16LE() method returns an integer that has a value offset plus the number of bytes written to the buffer.
The code snippet below demonstrates the use of the writeInt16LE() method:
const buff = Buffer.allocUnsafe(2);buff.writeInt16LE(0x1234, 0);console.log(buff);
In line 1, we declare a buffer, buff.
In line 3, the writeInt16LE() method is used to write 16 bits from index 0 in the little-endian format.
As one index of the buffer is 8 bits, we need to write at 2 indices.
The writeInt16LE() method writes at 2 indices of buff, starting from index 0, that is, index = 0 - index + 2 - 1 = 1.
Since the code is in the little-endian format, the index 1 is written before the index 0.