Friday, May 17, 2024
 Popular · Latest · Hot · Upcoming
84
rated 0 times [  90] [ 6]  / answers: 1 / hits: 36898  / 9 Years ago, thu, june 18, 2015, 12:00:00

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?


More From » node.js

 Answers
21

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

[#66157] Tuesday, June 16, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
tayla

Total Points: 681
Total Questions: 102
Total Answers: 108

Location: Marshall Islands
Member since Tue, Sep 21, 2021
3 Years ago
tayla questions
Fri, Mar 5, 21, 00:00, 3 Years ago
Wed, Oct 28, 20, 00:00, 4 Years ago
Thu, Apr 9, 20, 00:00, 4 Years ago
;