Convert 2 bytes in a buffer to integer

Please inquire about converting numbers.

Here is the buffered value.
[1,3,10,1,4] > msg.payload

Create a new buffer and truncate the item located at [3],[4]
var pay1= Buffer.alloc(2);

Then slice it again and turn it into a string.
var pay2=pay1.slice(0,4).toString('hex');

Then you get something like this:

So we convert this value to a number.
var pay3=Number(pay2);

Then it comes out in numeric form.
It comes out as 104 or 0x68.

the value i want is
It should come out as 0x104, the number 260.
But I keep getting 104 or 0x68.

Is there any way to solve this?

The code is organized as follows.

buffer [1,3,10,1,4]

var pay1= Buffer.alloc(2);
var pay2=pay1.slice(0,4).toString('hex');
var pay3=Number(pay2);
return msg;

That's how NodeJS Buffer.toString('hex') works. It's output is a hex string, but without the leading '0x'. By coincidence, your number doesn't contain digits with a to f, so the Number conversions thinks it's a decimal.

If you want to convert a Buffer part into a number, I suggest you use one of the many conversion functions, like readInt16LE([offset]). It's much easier and less error-prone.

See the docs for more methods like that: Buffer | Node.js v14.17.3 Documentation

Alternatively, there's an excellent node with does Buffer conversions for you:

thank you for the reply.

I solved the problem in another way.

I solved it as below.

var pay2=Buffer.alloc(2);
var pay3=pay2.slice(0,4).toString('hex');
var pay4=Number("0x"+pay3);

As @kuema suggested, this is far easier with buffer-parser...



If you insist on DIY then you should probably fix up your function code. There is no need to convert to hex string & append '0x0' and then parse it back to an integer.

Combining bytes to make an integer is as simple as shifting the one byte 8 places left then OR the 2 bytes...

msg.payload = msg.payload[3] << 8 | msg.payload[4];
return msg;


1 Like

thank you for the reply.
It is not possible to do it in the Buffer Node because some modifications have to be made in the function code.

We will refer to it next time.

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.