Trusted answers to developer questions

What is readInt16BE() Buffer module in Node.js?

Get the Learn to Code Starter Pack

Break into tech with the logic & computer science skills you’d learn in a bootcamp or university — at a fraction of the cost. Educative's hand-on curriculum is perfect for new learners hoping to launch a career.

Buffer objects are used to represent a sequence of bytes of pre-determined size. They are similar to arrays but cannot be resized. Since the Buffer class is designed to handle raw binary data, it provides various methods, particularly for binary data.

The readInt16BE method is used to read a signed, big-endian 16-bit integer at an offset provided in the function’s arguments. The bytes read from the buffer are represented as a two’s complement signed integer value.

Syntax and parameters

The method can be accessed using the . notation on a buffer object. In the following example, buf is a Buffer object.

buf.readInt16BE([offset])
  • Offset is the number of bytes to skip before reading the buffer. It is initialized with 0 by default. The offset must be between 0 and (buf.length - 2).

buf.length is the size of the buffer, i.e., the number of elements in the buffer.

Return value

The function returns a two’s complement signed integer.

Example

We will demonstrate how to use the readInt16BE in the following example:

const buf = Buffer.from([0x10, 0x20, 0x30, 0x40, 0x50, 0x60]);
console.log(buf.readInt16BE(0).toString(16));
console.log(buf.readInt16BE(3).toString(16));
//console.log(buf.readInt16BE(6).toString(16));
  • We first initialize the buffer using an array of hexadecimal numbers and the .from method of the Buffer object.
  • In line 3, the offset is set as 0. The first 2 values are printed.
  • In line 4, we provide an offset of 3. The first 3 values are skipped, and the next 2 values are printed.
  • You can comment out line 5 to check that the compiler throws an ERR_OUT_OF_RANGE (out of range) error when the offset is greater than the limit we described above in the heading Syntax and Parameters.

The toString method is used to convert the result into text. We provide 16 as the radix argument of the function to convert the result into a hexadecimal representation.

RELATED TAGS

node.js

CONTRIBUTOR

Adnan Abbas
Copyright ©2024 Educative, Inc. All rights reserved
Did you find this helpful?