Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

node.js
communitycreator

What is the Buffer.writeInt16LE() method in Node.js?

Syed Muhammad Ali Mustafa

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

The writeInt16LE() method

The writeInt16LE() method in Node.js writes a 16-bit unsigned integer at a specified offset from a buffer in the little-endianleast significant value is stored at the lowest storage address format.

Syntax

The writeInt16LE() method can be declared as shown in the code snippet below:


Buffer.writeInt16LE(value, offset)

Parameters

  • 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 offset should be range from 0 to (bufferLength - 2). The default value of offset is 0.


Return value

The writeInt16LE() method returns an integer that has a value offset plus the number of bytes written to the buffer.

Code

The code snippet below demonstrates the use of the writeInt16LE() method:

const buff = Buffer.allocUnsafe(2);
buff.writeInt16LE(0x1234, 0);
console.log(buff);

Explanation

  • 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.

RELATED TAGS

node.js
communitycreator

CONTRIBUTOR

Syed Muhammad Ali Mustafa

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring