当前位置 : 主页 > 网页制作 > Nodejs >

node.js – 错误:十六进制字符串无效

来源:互联网 收集:自由互联 发布时间:2021-06-16
这是我的节点js代码 if (protocol == '01') { console.log('...goint to get Ack Obj...'); var o = getAckObj(hexString); console.log('...ack obj received...'); var msg = ackMsg(o); console.log('..going to write buffer...'); socket.write(
这是我的节点js代码

if (protocol == '01') {
  console.log('...goint to get Ack Obj...');
  var o = getAckObj(hexString);
  console.log('...ack obj received...');
  var msg = ackMsg(o);
  console.log('..going to write buffer...');
  socket.write(new Buffer(msg, 'hex')); //, 'binary');
  console.log('Server sent welcome: ' + msg);
}

.....

function ackMsg(dataObj) {
  var ackText = '';
  dataObj.len = '05'; //for ack msg its always 05
  var e = crc16(dataObj.len + dataObj.protocol + dataObj.serial, 'hex');
  dataObj.error = e.toString(16);
  return dataObj.start + dataObj.len + dataObj.protocol + dataObj.serial + dataObj.error + dataObj.stop;
}

这是hexString中的值78780d010387113120864842000ccbe40d0a

在控制台输出

...goint to get Ack Obj...
...ack obj received...
..going to write buffer...
buffer.js:348
      ret = this.parent.hexWrite(string, this.offset + offset, length);
你确定你的弦的长度是均匀的吗?当您提供的十六进制字符串为奇数(len%2!= 0)而不是所需的偶数时,缓冲区会引发(不清楚)错误消息.

一个很好的测试是记录你拥有的十六进制字符串,然后在Python中尝试:

>>> '8'.decode('hex')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python2.7/encodings/hex_codec.py", line 42, in hex_decode
    output = binascii.a2b_hex(input)
TypeError: Odd-length string

我已经在GitHub上打开了一个pull-request来修复错误消息,使其更加清晰:https://github.com/nodejs/node/pull/4877/files

网友评论