Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

node.js

How to use the buf.writeInt8() function in Node.js

Ayesha Naeem

The buf.writeInt8() function writes a given value at a given offset in the buffer that calls the buf.writeInt8() function.

Prototype

Parameters and return value

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.

Example

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

node.js

CONTRIBUTOR

Ayesha Naeem
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring