The writeUInt8
function in Node.js comes with the Buffer
module and is used to write an 8-bit unsigned integer to a buffer at a specified offset.
To use the writeUInt8
function, we would need a pre-allocated buffer. For this tutorial, we have named it mybuffer
. The following syntax is used to use the writeUInt8
function:
mybuffer.writeUInt8(value, offset);
The writeUInt8
function takes in up to two parameters:
value
: the unsigned 8-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 one less than mybuffer.len
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. Ifvalue
is greater than 8 bits, the function exhibits undefined behavior.
The writeUInt8
returns the sum of the offset
and the number of bytes written to the buffer upon successful execution.
The program below allocates a buffer of length 5. Subsequently, it uses the writeUInt8
function to write an 8-bit unsigned integer to mybuffer
at a specified offset and prints the current state of mybuffer
using the console.log
function.
The program fills mybuffer
from 0 to 4 in reverse order and prints its final state before terminating.
mybuffer = Buffer.alloc(5);console.log(mybuffer);mybuffer.writeUInt8(0x01, 4);console.log(mybuffer);mybuffer.writeUInt8(0x02, 3);console.log(mybuffer);mybuffer.writeUInt8(0x03, 2);console.log(mybuffer);mybuffer.writeUInt8(0x04, 1);console.log(mybuffer);mybuffer.writeUInt8(0x05, 0);console.log(mybuffer);
Free Resources