writeUInt16BE()
methodThe writeUInt16BE()
method in Node.js
writes a 16 bits
unsigned integer at a specified offset from a buffer in the
The writeUInt16BE()
method can be declared as shown in the code snippet below:
Buffer.writeUInt16BE(value, offset)
value
: A 16 bit signed integer to be written in the buffer.
offset
: The offset determines the number of bytes to skip before writing to the buffer.
In other words, it is the index of the buffer.
- The value of
offset
should be range from0 to (bufferLength - 2)
.- The default value of
offset
is 0.
The writeUInt16BE()
method returns an integer that has a value offset
plus the number of bytes written to the buffer.
The code snippet below demonstrates the use of the writeUInt16BE()
method:
const buff = Buffer.allocUnsafe(2);buff.writeUInt16BE(0x1234, 0);console.log(buff);
In line 1, we declare a buffer, buff
.
The writeUInt16BE()
method is used in line 3 to write 16 bits from index 0 in the big-endian format.
As one index of the buffer is 8 bits, we need to write at 2 indices.
The writeUInt16BE()
method writes at 2 indices of buff
starting from index 0
i.e., index = 0
- index + 2 - 1 = 1
.
Since the code is in the Big Endian format, index 0 is written before index 1.