Open In App

Node.js Buffer.readUIntLE() Method

The Buffer.readUIntLE() method is an inbuilt application programming interface of class Buffer within the Buffer module which is used to read specified number of byte(s) value from an allocated buffer at a specified offset.

Syntax:



Buffer.readUIntLE( offset, byteLength )

Parameters: This method accept two parameters as mentioned above and described below:

Return Value: This method returns an integer value that read from buffer in Little Endian format.



Below examples illustrate the use of Buffer.readUIntLE() method in Node.js:

Example 1:




// Node program to demonstrate the  
// Buffer.readUIntLE() Method
   
// Allocating buffer from array
const buf = Buffer.from([0x21, 0x09, 0x19, 0x98]);
  
// Printing allocated buffer
console.log(buf);
   
// Reading data from the buffer
// and printing it as a string
console.log(buf.readUIntLE(0, 3).toString(16));
console.log(buf.readUIntLE(1, 3).toString(16));
console.log(buf.readUIntLE(2, 2).toString(16));

Output:

<Buffer 21 09 19 98>
190921
981909
9819

Example 2:




// Node program to demonstrate the  
// Buffer.readUIntLE() Method
   
// Allocating buffer from array
const buf = Buffer.from([0x21, 0x09, 0x19, 0x98]);
  
// Printing allocated buffer
console.log(buf);
   
// Reading data from the buffer
// and printing it as a string
console.log(buf.readUIntLE(0, 3).toString(16));
console.log(buf.readUIntBE(0, 3).toString(16));
console.log(buf.readUIntLE(1, 2).toString(16));
console.log(buf.readUIntBE(1, 2).toString(16));
console.log(buf.readUIntLE(2, 1).toString(16));
console.log(buf.readUIntBE(2, 1).toString(16));

Output:

<Buffer 21 09 19 98>
190921
210919
1909
919
19
19

Example 3:




// Node program to demonstrate the  
// Buffer.readUIntLE() Method
   
// Allocating buffer from array
const buf = Buffer.from([0x21, 0x09, 0x19, 0x98]);
  
// Printing allocated buffer
console.log(buf);
   
// Reading  data from the buffer
// and printing it as a string
console.log(buf.readUIntLE(0, 4).toString(16));
console.log(buf.readUIntLE(1, 2).toString(16));
console.log(buf.readUIntLE(2, 3).toString(16));
   
// Wrong index is provoded to produce error
console.log(buf.readUIntLE(3, 6).toString(16));

Output:

<Buffer 21 09 19 98>
98190921
1909
internal/buffer.js:49
  throw new ERR_OUT_OF_RANGE(type || 'offset',
  ^

RangeError [ERR_OUT_OF_RANGE]: The value of "offset" is out of range. 
It must be >= 0 and <= 1. Received 2
    at boundsError (internal/buffer.js:49:9)
    at readUInt24LE (internal/buffer.js:118:5)
    at Buffer.readUIntLE (internal/buffer.js:61:12)
    . . .

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

Reference: https://nodejs.org/api/buffer.html#buffer_buf_readuintle_offset_bytelength


Article Tags :