Wern Ancheta
Wern Ancheta

Reputation: 23297

How to convert Node.js buffer to integer in the client-side?

I'm trying to store an integer into a node.js buffer and then send it to the client-side via bleno:

var num = 24;
var buf = new Buffer(1);
buf.writeUInt8('0x' + num, 0);
//send buf using bleno

I then convert this to a string in the client-side with the following code:

function bytesToString(buffer) {    
  return String.fromCharCode.apply(null, new Uint8Array(buffer));
}

The problem is that I don't get the original value back (24). Instead what this returns is the '#' string. I also tried the solutions here: Converting between strings and ArrayBuffers but I either get chinese or unicode characters.

Here's what I was doing previously in the Node.js side and it works without any problems with the bytesToString function above:

new Buffer(num.toString());

But the requirements specified that I should send the integer or float without converting it to string. Is this possible? Any ideas what I am doing wrong? Thanks in advance.

Upvotes: 0

Views: 1873

Answers (1)

rsp
rsp

Reputation: 111336

When you're doing this:

buf.writeUInt8('0x' + num, 0);

you are already converting it to string by concatenating it with another string in '0x' + num so no matter what you do later, it has already been converted to string at this point - probably to a wrong string, because you're prepending the hexadecimal prefix to a number that is converted to a decimal by default.

What you're doing here is a very complicated and incorrect way of serializing the number that could easily be transferred as JSON.

Upvotes: 2

Related Questions