Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 807
kmachnicki Avatar asked Jun 18 '15 09:06

kmachnicki


People also ask

How do you convert a buffer to a string value?

In a nutshell, it's easy to convert a Buffer object to a string using the toString() method. You'll usually want the default UTF-8 encoding, but it's possible to indicate a different encoding if needed. To convert from a string to a Buffer object, use the static Buffer.

How do you convert a buffer to a string value in node JS?

Buffers have a toString() method that you can use to convert the buffer to a string. By default, toString() converts the buffer to a string using UTF8 encoding. For example, if you create a buffer from a string using Buffer. from() , the toString() function gives you the original string back.

What is buffer type in JavaScript?

The Buffer class in Node. js is designed to handle raw binary data. Each buffer corresponds to some raw memory allocated outside V8. Buffers act somewhat like arrays of integers, but aren't resizable and have a whole bunch of methods specifically for binary data.


2 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 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];
like image 55
mscdex Avatar answered Oct 22 '22 21:10

mscdex


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

const integer = parseInt(buffer.toString("hex"), 16)
like image 24
Ernest Okot Avatar answered Oct 22 '22 20:10

Ernest Okot