22

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?

0

3 Answers 3

44

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];
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks! Must've missed that readUIntBE function. It works perfectly.
To save a few microseconds: var decimal = (((buffer[0] << 8) + (buffer[1]) << 8) + buffer[2];
Little endian variant: (bytes[2] << 16) | (bytes[1] << 8) | bytes[0]
4

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

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

3 Comments

This worked great for me. I just want text categories to semi randomly get assigned a colour number from a fixed palette of colours.
Nice! @JoshPeak
This is perfect.
-3

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.