What is the writeUInt16LE function in Node.js?

The writeUInt16LE function in Node.js comes with the Buffer module and is used to write a 16-bit unsigned integer in Little Endian format to a buffer at a specified offset.

In Little Endian format, the least significant bits are written first. For example, the 16-bit hex number AB CD would be represented as CD AB in Little Endian format.

Syntax

To use the writeUInt16LE function, we would need a pre-allocated buffer. For this tutorial, we have named it mybuffer. The following syntax is used to use the writeUInt16LE function:

mybuffer.writeUInt16LE(value, offset);

Parameters

The writeUInt16LE function takes in two parameters:

  • value: the unsigned 16-bit integer that needs to be written to a pre-allocated buffer.
  • offset (optional): the offset at or the number of bytes after which value will be written to in the buffer. The minimum value of offset is 0, and its maximum value is two less than the value of mybuffer.lenwhich is the number of bytes in the buffer.

If offset is not specified, it is assumed to be 0 by default. If the value of offset is out of the prescribed range, the ERR_OUT_OF_RANGE error is thrown. If the value is greater than 16 bits, the function exhibits undefined behavior.

Return value

The writeUInt16LE function returns the sum of the offset and the number of bytes written to the buffer, upon successful execution.

Example

The program below allocates a buffer that is 6 bytes long. Subsequently, it uses the writeUInt16LE function to write a 16-bit unsigned integer to mybuffer at a specified offset, then prints the current state of mybuffer using the console.log function.

The program fills mybuffer with three 16-bit unsigned integers and prints its final state before terminating.

mybuffer = Buffer.alloc(6);
console.log(mybuffer);
mybuffer.writeUInt16LE(0xabcd, 0);
console.log(mybuffer);
mybuffer.writeUInt16LE(0xdbac, 2);
console.log(mybuffer);
mybuffer.writeUInt16LE(0xadeb, 4);
console.log(mybuffer);
Copyright ©2024 Educative, Inc. All rights reserved