我在Node.js中使用Socket来获取数据,并使用utf8格式将其保存在缓冲区中。这些数据是数字,我想进行一些计算,但结果为NaN。

var client = new net.Socket();
client.connect(PORT, HOST, function() {
    var commandstr = new Buffer("A5021E", "hex")
    client.write(commandstr);
});

client.on('data', function(data) {
    var buff = new Buffer(data, 'utf8');
    ProcessBuffer(buff);
    client.destroy();
});

client.on('close', function() {
    console.log('Connection closed');
});

ProcessBuffer = function(recv_msg){
    var bp_s = recv_msg.toString('utf8').substring(65, 69);

    console.log(parseInt(bp_s + 5)); //Do the calculation here and return in NaN
}

最佳答案

您需要先将字符串形式的bp_s变量转换为数字,然后再将其添加到5。

您可以使用parseInt函数[1]:parseInt(bp_s)

因此,您的最后一行是:

console.log(parseInt(bp_s) + 5);


请注意,parseInt函数还允许您定义数字的基数,作为该函数的第二个参数。默认情况下是10。

[1] https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt

关于javascript - 在UTF-8中计算两个数字,在Node.js中获得NaN,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/34878727/

10-12 20:42