Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

node.js
communitycreator

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

Gutha Vamsi Krishna

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

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))

RELATED TAGS

node.js
communitycreator

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring