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

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

Prototype

Parameters and return value

The buf.writeInt32LE() function accepts the following two 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 - 4. The default value of offset is 0.

The buf.writeInt32LE() function returns the number of bytes written plus the offset as an integer value.

The value must be a 32-bit signed integer and is written to the buffer in the little-endian format.

In the little-endian format, the least significant byte is stored first and the most significant byte is stored last. For example, a hexadecimal value A1B2C3 will be stored as C3B2A1 in the little-endian format.

Example

The following example demonstrates how to write a 32-bit signed integer to a buffer.

//create a buffer
var buffer = Buffer.alloc(10)
console.log(buffer)
//define value
value = 0x19283746
//write to buffer
buffer.writeInt32LE(value, 2)
console.log(buffer)

The program creates a buffer of zeros of size 10 bytes. It then defines the value and writes it to the buffer starting from the third byte. The values in the buffer are in the little-endian format as illustrated.

The program will display an undefined behavior if the value is not a signed integer.

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved