Whats is the Buffer.writeIntBE() method in Nodejs?

In Nodejs, the Buffer.writeIntBE() method writes up 4848 bits of value to the buffer as a signed integer.

It writes to the buffer in the Big Endian format.

Endianness

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

  1. Little Endian
  2. Big Endian.

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

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

Syntax


buf.writeIntBE(value, offset, byteLength)

Parameters

  • value: The value of the unsigned integer to be written to the buffer of the BigInt type.

  • 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 - byteLength.

  • byteLength: byteLength specifies the number of bytes to write to the buffer. The value of byteLength must be greater than 00 and byteLength <= 6.

    It should be less than equal to 66 because the Buffer.writeIntBE() method gives a maximum of 48 bits of accuracy.

Return value

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

Code

const buf = Buffer.alloc(6);
buf.writeIntBE(0x12, 3, 2);
console.log(buf);

Explanation

We create a buffer called buf in the code above and allocate 6 bytes of memory. Then, the value 0x12 is written to the buffer at the offset 3 and the byteLength 2.

This pads the value 0x12 until it takes 2 bytes of memory, making it 0x0012.

Hence, when we print the buf contents in line 33, 0x12 prints out at the 4th index instead of the 3rd.

Free Resources