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
buffrom fill as[-1,127]. -
In lines 3 and 4, we print the integers (read as signed 8-bit) to the console.
//construcing buffer objectconst buf = Buffer.from([-1, 127]);//reading as signed 8 bitconsole.log(buf.readInt8(0));console.log(buf.readInt8(1))
Example 2
In the below code:
- We construct the buffer object
buffrom fill[129]. - Since it is out of signed
8bit range-128to+127,+129is represented as-127. First, it fills until127in memory, but we have left-128to0to store. So, we store the remaining128and129in negative places, as+128will store in-128and+129will store in-127. - We run the code snippet and see two different outputs, one reading as normal integer
129and the other reading as signed 8-bit integer-127.
//construcing buffer objectconst buf = Buffer.from([129])//This will be read as normal integerconsole.log(buf[0])//This will be read as signed 8 bit integer.console.log(buf.readInt8(0))