The writeUInt16BE
function in Node.js comes with the Buffer
module and is used to write a 16-bit unsigned integer in the Big Endian format to a buffer at a specified offset.
In the Big Endian format, the least significant bits are written last. In Little Endian format, this order is reversed. For example, the 32-bit hex number AB CD AD BD would be represented as BD AD CD AB in Little Endian format, and as AB CD AD BD in Big Endian format.
To use the writeUInt16BE
function, we need a pre-allocated buffer. For this tutorial, we have named it mybuffer
. The following syntax is used to use the writeUInt16BE
function:
mybuffer.writeUInt16BE(value, offset);
The writeUInt16BE
function takes in two parameters:
value
: the unsigned 16-bit integer that needs to be written to a pre-allocated buffer.offset
(optional): the offset at or the number of bytes after which value
will be written to in the buffer. The minimum value of offset
is 0, and its maximum value is two less than the value of mybuffer.len
, which is the number of bytes in the buffer.If
offset
is not specified, it is assumed to be 0 by default. If the value ofoffset
is out of the prescribed range, theERR_OUT_OF_RANGE
error is thrown. If thevalue
is greater than 16 bits, the function exhibits undefined behavior.
The writeUInt16BE
function returns the sum of the offset
and the number of bytes written to the buffer upon successful execution.
The program below allocates a buffer that is 6 bytes long. Subsequently, it uses the writeUInt16BE
function to write a 16-bit unsigned integer to mybuffer
at a specified offset, then prints the current state of mybuffer
using the console.log
function.
The program fills mybuffer
with three 16-bit unsigned integers and prints its final state before terminating.
mybuffer = Buffer.alloc(6);console.log(mybuffer);mybuffer.writeUInt16BE(0xabcd, 0);console.log(mybuffer);mybuffer.writeUInt16BE(0xdbac, 2);console.log(mybuffer);mybuffer.writeUInt16BE(0xadeb, 4);console.log(mybuffer);
Free Resources