JavaScript: reading 3 bytes Buffer as an integer

Let's say I have a hexadecimal data stream that I want to split into 3-byte blocks, which I need to read as a whole.

For example: with the given hexadecimal string 01be638119704d4b9a I need to read the first three bytes of 01be63 and consider it an 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); 

readUInt32BE works fine for 4-byte 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 did I read 3 bytes correctly as a whole?

+16
javascript buffer
source share
3 answers

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 these are readUIntBE for Big Endian and readUIntLE for Little Endian).

Otherwise, if you are using an older version of the node, you will have to do it manually (check the boundaries first):

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

I use this, if someone knows something is wrong with this, please let me know;

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

you must convert three bytes to four bytes.

 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 feature.

-4
source share

All Articles