Node.js Buffer.readUInt16BE() Method
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:
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:
const buf = Buffer.from([0x21, 0x09, 0x19, 0x98]);
console.log(buf);
console.log(buf.readUInt16BE(0).toString(16));
console.log(buf.readUInt16BE(1).toString(16));
console.log(buf.readUInt16BE(2).toString(16));
|
Output:
<Buffer 21 09 19 98>
2109
919
1998
Example 2:
const buf = Buffer.from([0x21, 0x09, 0x19, 0x98]);
console.log(buf);
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));
|
Output:
<Buffer 21 09 19 98>
2109
921
919
1909
1998
9819
Example 3:
const buf = Buffer.from([0x21, 0x09, 0x19, 0x98]);
console.log(buf);
console.log(buf.readUInt16BE(0).toString(16));
console.log(buf.readUInt16BE(1).toString(16));
console.log(buf.readUInt16BE(2).toString(16));
console.log(buf.readUInt16BE(3).toString(16));
|
Output:
<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
Last Updated :
13 Oct, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...