JavaScript: reading 3 bytes Buffer as an integer

kmachnicki picture kmachnicki · Jun 18, 2015 · Viewed 30k times · Source

Let's say I have a hex data stream, which I want to divide into 3-bytes blocks which I need to read as an integer.

For example: given a hex string 01be638119704d4b9a I need to read the first three bytes 01be63 and read it as integer 114275. This is what I got:

var sample = '01be638119704d4b9a';
var buffer = new Buffer(sample, 'hex');
var bufferChunk = buffer.slice(0, 3);
var decimal = bufferChunk.readUInt32BE(0);

The readUInt32BE works perfectly for 4-bytes data, but here I obviously get:

RangeError: index out of range
  at checkOffset (buffer.js:494:11)
  at Buffer.readUInt32BE (buffer.js:568:5)

How do I read 3-bytes as integer correctly?

Answer

mscdex picture mscdex · Jun 18, 2015

If you are using node.js v0.12+ or io.js, there is buffer.readUIntBE() which allows a variable number of bytes:

var decimal = buffer.readUIntBE(0, 3);

(Note that it's readUIntBE for Big Endian and readUIntLE for Little Endian).

Otherwise if you're on an older version of node, you will have to do it manually (check bounds first of course):

var decimal = (buffer[0] << 16) + (buffer[1] << 8) + buffer[2];