简体   繁体   English

如何在客户端将Node.js缓冲区转换为整数?

[英]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 : 我正在尝试将一个整数存储到node.js缓冲区中,然后通过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). 问题在于我没有收回原始价值(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. 我也在这里尝试了解决方案: 在字符串和ArrayBuffers之间转换,但是我得到了中文字符或unicode字符。

Here's what I was doing previously in the Node.js side and it works without any problems with the bytesToString function above: 这是我之前在Node.js方面所做的事情,并且上面的bytesToString函数没有任何问题,可以正常工作:

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. 提前致谢。

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. 您已经通过将其与'0x' + num另一个字符串连接而将其转换为字符串,因此无论您以后做什么,此刻它都已转换为字符串-可能是错误的字符串,因为您要在数字的十六进制前缀,默认情况下会转换为十进制。

What you're doing here is a very complicated and incorrect way of serializing the number that could easily be transferred as JSON. 您在这里所做的是序列化数字的一种非常复杂且不正确的方法,该数字可以轻松地转换为JSON。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM