用 UTF-8 计算两个数字,在节点.js中得到 NaN

Calculate two number in UTF-8 get NaN in Node.js

本文关键字:js 节点 NaN 数字 计算 UTF-8 两个      更新时间:2023-09-26

我在 Node 中使用套接字.js来获取数据并使用 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