What is the Node.js Buffer.writeInt32LE() method in Node.js?

The Buffer.writeInt32() method in Node.js is used to write a 32-bit signed Integer value to a specific location in the Little Endian buffer format.

Endianness

The endianness of data refers to the order of bytes in the data. There are two types of Endianness:

  • Little Endian
  • Big Endian

Little Endian stores the Least Significant Byte (LSB) first and is commonly used in Intel processors.

Big Endian stores the Most Significant Byte (MSB) first. It is also called ‘Network Byte Order’ because most networking standards expect the MSB first.

The illustration below shows the difference between the Big Endian and Little Endian.

Note: writeInt32LE interprets the number as a two’s compliment signed number.

Syntax

buf.writeInt32LE(value[, offset])

Parameters

  • value: The value of the unsigned integer to be written to the buffer.
  • offset: The offset from the starting position where the value will be written. The default value for offset is 00. The offset must be between 00 and buffer.length - 4.

Return value

buffer.writeUInt32LE() returns the offset plus the number of bytes written to the buffer.

Exceptions

The behavior of buffer.writeUInt32LE() is undefined if the value is anything other than a 32-bit signed Integer.

Code

const buf = Buffer.alloc(4);
buf.writeInt32LE(0x11000045, 0);
console.log(buf);

Explanation

The first line in the code creates a buffer (buf) and allocates 4-bytes of memory to it.

Next, we write the value 0x11000045, which is a 32-bit integer value where the MSB is 0xff and the LSB is 0x32, using the following line:

buf.writeInt32LE(0x11000045, 0)

In the last line, we print out the contents of the buffer to the Standard Output. As we can see, the contents are printed in the Little Endian format, where the least significant byte is stored first, and the most significant byte is stored last.

Free Resources