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:
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.
Buffer.readInt8( offset )
Offset: specifies the number of bytes to skip before starting to read.The Buffer.readInt8() method returns the signed 8-bit integer.
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 objectconst buf = Buffer.from([-1, 127]);//reading as signed 8 bitconsole.log(buf.readInt8(0));console.log(buf.readInt8(1))
In the below code:
buf from fill [129].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.129 and 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))