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.
The endianness of data refers to the order of bytes in the data. There are two types of Endianness:
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.
buf.writeIntBE(value, offset, byteLength)
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 .
The offset
must be between and buffer.length - byteLength
.
byteLength
: byteLength
specifies the number of bytes to write to the buffer. The value of byteLength
must be greater than and byteLength <= 6
.
It should be less than equal to because the Buffer.writeIntBE()
method gives a maximum of 48 bits of accuracy.
buffer.writeUIntBE()
returns the offset plus the number of bytes written to the buffer.
const buf = Buffer.alloc(6);buf.writeIntBE(0x12, 3, 2);console.log(buf);
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.