Home > Enterprise >  What does readUint8 do?
What does readUint8 do?

Time:12-13

const buff = Buffer.from('15') returns a length=2 array of 8 bit bytes, and logs the hex code. Example: <Buffer 31 35>

If I use the buff.readUint8() which takes an [offset] parameter or otherwise takes the first byte in the array, what is this function doing?

The output is 49.

CodePudding user response:

readUint8() takes a single 8-bit byte from a buffer, interprets it as an unsigned value (so it allows the high bit to be part of the value, not representing a sign) and then converts that 8-bits into a Javascript number (which is a double precision float) so you can then use that value as a number in Javascript.

In your specific example of:

<Buffer 31 35>

This is a buffer of binary data that contains two values with hex values of 0x31 and 0x35?

readUnint8() allows you to extract a single 8-bit value from that buffer and convert it to the appropriate Number format in Javascript so it can be used as a number. Other similar functions, such as .readUInt16BE() allow you to combine more than one byte into a number and to specify the order of those bytes (big-endian or little-endian, formats used by different compute architectures) and specify the sign interpretation as well.

The source of data like this is often code written in a lower level language that saves or sends binary data. That binary data has to be interpreted at the other end by some code that knows the layout of the specific bytes and these Buffer functions allow you to properly interpret that data. The code trying to understand this data has to know in advance the format of the data so it can use the correct functions for interpreting it.

For example, you may have a packet of binary data arriving on a TCP connection that contains structured data that needs to be interpreted like this:

32 bit unsigned integer (in little-endian format)
32-bit signed integer   (in little-endian format)
8-bit unsigned character code
8-bit unsigned character code
8-bit unsigned character code
8-bit unsigned character code

To do that, you would use the appropriate buffer methods to read these various values out of a Buffer, while having them converted to the desired value in Javascript and interpreted correctly.

  • Related