What is the Node.js Buffer.readInt8() method?

Definition

The Buffer.readInt8() method reads signed 8-bit integers from a buffer object at the specified object.

Integers that are read from a Buffer are interpreted as two’s complement signed values, which means:

  • Anything that is stored in the computer’s memory will be stored as 0’s and 1’s.
  • We can represent +5 as 00000101 in 8-bits, but to represent -5 we take two’s complement of 5, i.e., 11111011.
  • The readInt8() method reads integers as two’s complement.

The range of a signed byte using two’s complement for 8-bit is from -128 to 127.

Syntax

Buffer.readInt8( offset )

Parameters

  • Offset: specifies the number of bytes to skip before starting to read.

Return value

The Buffer.readInt8() method returns the signed 8-bit integer.

Example 1

The example below shows how to use the readInt8() method.

  • In line 1, we construct the buffer object buf from fill as [-1,127].

  • In lines 3 and 4, we print the integers (read as signed 8-bit) to the console.

//construcing buffer object
const buf = Buffer.from([-1, 127]);
//reading as signed 8 bit
console.log(buf.readInt8(0));
console.log(buf.readInt8(1))

Example 2

In the below code:

  • We construct the buffer object buf from fill [129].
  • Since it is out of signed 8 bit range -128 to +127, +129 is represented as -127. First, it fills until 127 in memory, but we have left -128 to 0 to store. So, we store the remaining 128 and 129 in negative places, as +128 will store in -128 and +129 will store in -127.
  • We run the code snippet and see two different outputs, one reading as normal integer 129 and the other reading as signed 8-bit integer -127.
//construcing buffer object
const buf = Buffer.from([129])
//This will be read as normal integer
console.log(buf[0])
//This will be read as signed 8 bit integer.
console.log(buf.readInt8(0))

Free Resources