Node.js Buffer.readUInt16BE() Method
Last Updated :
13 Oct, 2021
Improve
The Buffer.readUInt16BE() method is an inbuilt application programming interface of class Buffer within the Buffer module which is used to read 16-bit value from an allocated buffer at a specified offset.
Syntax:
javascript
Output:
javascript
Output:
javascript
Output:
Buffer.readUInt16BE( offset )Parameters: This method accepts single parameter offset that specifies the number of bytes to skip before read or simply signify the index in the buffer. The value of buffer lies 0 <= offset <= Buffer.length - 2. Its default value is 0. Return Value: This method returns an unsigned 16-bit integer value that is read from buffer in big endian format (Buffer.readUInt16LE() read 16 bit in little endian format). Below examples illustrate the use of Buffer.readUInt16BE() method in Node.js: Example 1:
// Node.js program to demonstrate the
// Buffer.readUInt16BE() method
// Allocating buffer from array
const buf = Buffer.from([0x21, 0x09, 0x19, 0x98]);
// Printing allocated buffer
console.log(buf);
// Reading 16bits data from the buffer
// and printing it as a string
console.log(buf.readUInt16BE(0).toString(16));
console.log(buf.readUInt16BE(1).toString(16));
console.log(buf.readUInt16BE(2).toString(16));
<Buffer 21 09 19 98> 2109 919 1998Example 2:
// Node.js program to demonstrate the
// Buffer.readUInt16BE() method
// Allocating buffer from array
const buf = Buffer.from([0x21, 0x09, 0x19, 0x98]);
// Printing allocated buffer
console.log(buf);
// Reading 16bits data from the buffer
// and printing it as a string
console.log(buf.readUInt16BE(0).toString(16));
console.log(buf.readUInt16LE(0).toString(16));
console.log(buf.readUInt16BE(1).toString(16));
console.log(buf.readUInt16LE(1).toString(16));
console.log(buf.readUInt16BE(2).toString(16));
console.log(buf.readUInt16LE(2).toString(16));
<Buffer 21 09 19 98> 2109 921 919 1909 1998 9819Example 3:
// Node.js program to demonstrate the
// Buffer.readUInt16BE() method
// Allocating buffer from array
const buf = Buffer.from([0x21, 0x09, 0x19, 0x98]);
// Printing allocated buffer
console.log(buf);
// Reading 16bits data from the buffer
// and printing it as a string
console.log(buf.readUInt16BE(0).toString(16));
console.log(buf.readUInt16BE(1).toString(16));
console.log(buf.readUInt16BE(2).toString(16));
// Wrong index is provided to produce error
console.log(buf.readUInt16BE(3).toString(16));
<Buffer 21 09 19 98> 2109 919 1998 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 <= 2. Received 3 at boundsError (internal/buffer.js:49:9) at Buffer.readUInt16BE (internal/buffer.js:215:5) . . .Note: The above program will compile and run by using the
node index.js
command.
Reference: https://nodejs.org/api/buffer.html#buffer_buf_readuint16be_offset