Whats is the Buffer.writeIntBE() method in Nodejs?
In Nodejs, the Buffer.writeIntBE() method writes up 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:
- Little Endian
- 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 theBigInttype. -
offset: The offset from the starting position where thevaluewill be written. The default value foroffsetis .The
offsetmust be between andbuffer.length - byteLength. -
byteLength:byteLengthspecifies the number of bytes to write to the buffer. The value ofbyteLengthmust be greater than andbyteLength <= 6.It should be less than equal to 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 , 0x12 prints out at the 4th index instead of the 3rd.