kmachnicki
kmachnicki

Reputation: 365

JavaScript: reading 3 bytes Buffer as an integer

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?

Upvotes: 22

Views: 38345

Answers (3)

mscdex
mscdex

Reputation: 106696

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];

Upvotes: 44

Ernest Okot
Ernest Okot

Reputation: 988

I'm using this, if someone knows something wrong with it, please advise;

const integer = parseInt(buffer.toString("hex"), 16)

Upvotes: 4

BlackMamba
BlackMamba

Reputation: 10254

you should convert three byte to four byte.

function three(var sample){
    var buffer = new Buffer(sample, 'hex');

    var buf = new Buffer(1);
    buf[0] = 0x0;

    return Buffer.concat([buf, buffer.slice(0, 3)]).readUInt32BE();
}

You can try this function.

Upvotes: -3

Related Questions