0

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.

1 Answer 1

2

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.

3
  • so what do you suggest I would do? using buf.writeUInt8(0x24, 0) changes the character to '$' instead when bytesToString() function is used. Commented Mar 6, 2017 at 11:48
  • @WernAncheta That's right, because 0x24 is the ASCII value of the '$' character. When you later convert that buffer to a string then you get the dollar sign as you should expect. What I would suggest would be to use JSON or XML or some other well tested serialization instead of inventing your own, especially when you have problems with that.
    – rsp
    Commented Mar 6, 2017 at 11:57
  • thanks for your response, I really appreciate it. The problem is that these values are sent using bluetooth low energy and are sent at a specific interval so I can't really use JSON or XML. I guess I'm on the right track if its the ASCII equivalent. How do you suggest I get back the original value from this? I just found this: stackoverflow.com/questions/20580045/… I think it should work. Commented Mar 6, 2017 at 12:06

Not the answer you're looking for? Browse other questions tagged or ask your own question.