The readUInt8()
method reads an unsigned 8-bit integer from the buffer object at the specified offset and returns an integer.
An unsigned 8-bit integer is an unsigned whole or natural number ranging from 0 to +255.
buffer.readUInt8( offset )
offset
: Number of bytes to skip before starting to read. Offset must be in the range 0 <= offset <= buf.length - 1
. The default value of the offset is 0
.In the following example:
1
, we construct the buffer object from [1,255]
.4
, we print an unsigned 8-bit integer of 1
.7
, we print an unsigned 8-bit integer of 255
.const buf = Buffer.from([1, 255]);//since we passed 0 as parameter, it will first element i.e 1console.log(buf.readUInt8(0));//since we passed 1 as parameter, it will second element i.e 255console.log(buf.readUInt8(1));
In the following example:
7
, we are trying to read -2
. It won’t print -2
, but it prints 254
, since an unsigned 8-bit integer only holds 0 to +255
. So, -1
will be stored as 255
, and -2
will be stored as 254
.const buf = Buffer.from([1, -2]);//since we passed 0 as parameter, it will first element i.e 1console.log(buf.readUInt8(0));//since we passed 1 as parameter, it will first element i.e -2console.log(buf.readUInt8(1));
The method throws an error when we try to provide an offset outside of the range.
In the following code snippet, we pass offset as 3
. Since it is outside of the range for the buffer object buf
, it will raise the error RangeError [ERR_OUT_OF_RANGE]
.
const buf = Buffer.from([1, 255]);//passing offset outside of rangeconsole.log(buf.readUInt8(3));
RELATED TAGS
CONTRIBUTOR