The buf.writeInt8()
function writes a given value at a given offset in the buffer that calls the buf.writeInt8()
function.
The buf.writeInt8()
function accepts the following three parameters:
value
: The value that is written to the buffer.offset
: The position in the buffer where the value is written. An offset
of 3 would mean the value is written at the fourth-byte position. offset
must fulfill the condition 0 <= offset <= buf.length - byteLength
, and is set to 0 by default.The buf.writeInt8()
function returns the number of bytes written plus the offset as an integer value.
The value
must be an 8-bit signed integer.
An 8-bit signed integer has a range of -128 to 127, whereas an 8-bit unsigned integer has a range of 0 to 255.
The following example demonstrates how to write an 8-bit signed value to a buffer.
//create buffer const buffer = Buffer.alloc(4) console.log(buffer) //define value const val1 = 88 const val2 = 23 const val3= -45 //write to buffer buffer.writeInt8(val1, 0) buffer.writeInt8(val2, 1) buffer.writeInt8(val3, 2) console.log(buffer)
The program creates a buffer of zeros of size 4 bytes. It then defines three values and writes them to the buffer with appropriate offsets.
The program will display an undefined behavior if the value is not a signed integer.
RELATED TAGS
CONTRIBUTOR
View all Courses