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?
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.
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.
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.
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];
I'm using this, if someone knows something wrong with it, please advise;
const integer = parseInt(buffer.toString("hex"), 16)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With