Node.js | Buffer.readUInt16LE() Method

The Buffer.readUInt16LE() method is an inbuilt application programming interface of class Buffer within Buffer module which is used to read an unsigned 16-bit integer from buffer at the specified offset with specified little endian format.

Syntax:

Buffer.readUInt16LE( offset )

Parameters: This method accepts single parameter offset which denotes the number of bytes to skipped before starting to read from buffer. The offset can be in range 0 <= offset <= buf.length – 2. The default value of offset is 0.



Return value: It returns an integer from the specified offset in little endian format.

Below examples illustrate the use of Buffer.readUInt16LE() Method in Node.js:

Example 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

// Node.js program to demonstrate the 
// Buffer.readUInt16LE() method 
      
// Creating a buffer 
const buf = Buffer.from([0x7, 0x0,
       0x1, 0x1, 0x4, 0x5, 0x4, 0x6]); 
  
// Using Buffer.readUInt16LE() method
console.log(buf.readUInt16BE(0).toString(16));
  
// Using Buffer.readUInt16LE() method
console.log(buf.readUInt16BE(6).toString(16));
  
// Using Buffer.readUInt16LE() method
console.log(buf.readUInt16BE(2).toString(16));

chevron_right


Output:

700
406
101

Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

// Node.js program to demonstrate the 
// Buffer.readUInt16LE() method 
      
// Creating a buffer 
const buf = Buffer.from([0x1714, 0x1024, 0x2113,
       0x2121, 0x1245, 0x1675, 0x1725, 0x1856]); 
  
// Using Buffer.readUInt16LE() method
console.log(buf.readUInt16BE(0).toString(16));
  
// Using Buffer.readUInt16LE() method
console.log(buf.readUInt16BE(6).toString(16));
  
// Using Buffer.readUInt16LE() method
console.log(buf.readUInt16BE(10).toString(16));

chevron_right


Output:

1424
2556
RangeError [ERR_OUT_OF_RANGE]: The value of "offset" is out ofrange. 
It must be >= 0 and <= 6. Received 10    at boundsError (internal/buffer.js:49:9)
    at Buffer.readUInt16BE (internal/buffer.js:215:5)
    at /home/runner/index.js:14:17
    ......

The above example shows the error because its parameters are not in the valid range.

Note: The above program will compile and run by using the node index.js command.

Reference: https://nodejs.org/dist/latest-v13.x/docs/api/buffer.html#buffer_buf_readuint16le_offset



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.