The writeUIntBE
function in Node.js comes with the Buffer
module and is used to write an unsigned integer in the Big Endian format to a buffer at a specified offset. The maximum integer size here is 6 bytes.
In 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 writeUIntBE
function, we would need a pre-allocated buffer. For this tutorial, we have named it mybuffer
. The following syntax is used to use the writeUIntBE
function:
mybuffer.writeUIntBE(value, offset, length);
The writeUIntBE
function takes in three parameters:
value
: the unsigned integer that needs to be written to a pre-allocated buffer.offset
: the offset at or the number of bytes after which value
will be written in the buffer. The minimum value of offset
is 0, and its maximum value is the number length
less than the value of mybuffer.len
, which is the number of bytes in the buffer.If the value of
offset
is out of the prescribed range, theERR_OUT_OF_RANGE
error is thrown. Iflength
is greater than 6, the function exhibits undefined behavior.
length
: size, in bytes, of value
. Its value must be greater than 0 and smaller than or equal to 6.The writeUIntBE
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 8 bytes long. Subsequently, it uses the writeUIntBE
function to write a 2 byte and a 6 byte unsigned integer to mybuffer
at specified offsets, then prints the state of mybuffer
using the console.log
function.
The program fills mybuffer
with unsigned integers and prints its final state before terminating.
mybuffer = Buffer.alloc(8);console.log(mybuffer);mybuffer.writeUIntBE(0xabcd, 0, 2);console.log(mybuffer);mybuffer.writeUIntBE(0xdbacab125678, 2, 6);console.log(mybuffer);
Free Resources