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

The Buffer.readUInt16LE() method in Node.js is used to read 16 bits from a specified offset from a buffer in Little Endianthe least significant value is stored at the lowest storage address format.

Syntax

The Buffer.readUInt16LE() method can be declared as shown in the code snippet below:


Buffer.readUInt16LE(offset)

Parameter

offset: The offset determines the number of bytes to skip before reading the buffer.

In other words, it is the index of the buffer.

  • The offset value should be greater than -1 and less than (bufferLength - 1).
  • The default value of offset is 0.

Return value

The readUInt16LE() method returns a 16 bit integer.

Code

Consider the code snippet below, which demonstrates the use of the readUInt16LE() method:

const buff = Buffer.from([0x12, 0x34, 0x56, 0x78]);
console.log("buff stored in memory as", buff);
console.log("Reading at offset 0:", buff.readUInt16LE(0).toString(16));
console.log("Reading at offset 1:", buff.readUInt16LE(1).toString(16));
console.log("Reading at offset 2:", buff.readUInt16LE(2).toString(16));

Explanation

  • A buffer buff is declared in line 1.

  • The readUInt16LE() method is used in line 5 to get 16 bits from the index 0 in the little-endian format.

As one index of the buffer is 8 bits, we need to read 2 indices of the buffer.

The readUInt16LE() returns two indices of buff staring from index 0, i.e., index = 0 and index + 1 = 1.

As the format is little-endian, the indices are printed in reverse order (index 1 printed before index 0).

  • The readUInt16LE() method is used in line 6 to get 16 bits from the index 1 in little-endian format.

    As one index of the buffer is 8 bits, we need to read 2 indices of the buffer. The readUInt16LE() returns two indices of buff starting from index 1 i.e. index = 1 and index + 1 = 2.

    As the format is little-endian, the indices are printed in reverse order (index 2 printed before index 1).

  • The readUInt16LE() method is used in line 7 to get 16 bits from the index 2 in little-endian format.

    As one index of the buffer is 8 bits, we need to read 2 indices of the buffer. The readUInt16LE() returns two indices of buff starting from index 2 i.e. index = 2 and index + 1 = 3.

    As the format is little-endian, the indices are printed in reverse order (index 3 printed before index 2).

Free Resources