错误:十六进制字符串无效

时间:2014-02-26 13:19:33

标签: node.js

这是我的节点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);

2 个答案:

答案 0 :(得分:1)

你确定弦的长度是均匀的吗?当您提供的十六进制字符串为奇数(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

答案 1 :(得分:0)

如今,我也使用旧的io.js遇到了这个问题,其节点版本为1.2。

这是一个代码示例,其中出现了您这样的错误:

<?xml version="1.0" encoding="utf-8"?>
<paths>
    <files-path
        name="share"
        path="external_files"/>
</paths>

我检查了const resultBuffer = new Buffer.concat(chunks.items); fs.writeFileSync(resultFilePath, resultBuffer, {encoding: 'hex'}); 的两倍,然后使用简单的十六进制奇数值(如@JJ Geewax提到的),发现我的问题是节点fs模块和Buffer之间的交互。

要使其正常工作,我已从将原始缓冲区传递到具有正确编码的字符串中进行了更改:

chunks.items

也许有人觉得这很有用。