coure2011
coure2011

Reputation: 42474

Error: Invalid hex string

Here is my node js code

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;
}

Here is the value in hexString 78780d010387113120864842000ccbe40d0a

On console out put

...goint to get Ack Obj...
...ack obj received...
..going to write buffer...
buffer.js:348
      ret = this.parent.hexWrite(string, this.offset + offset, length);

Upvotes: 4

Views: 11970

Answers (2)

Vlad Moyseenko
Vlad Moyseenko

Reputation: 223

I've bumped into this issue too nowadays with an old io.js, the node version was 1.2.

Here is a code sample where I got such error as you:

const resultBuffer = new Buffer.concat(chunks.items);
fs.writeFileSync(resultFilePath, resultBuffer, {encoding: 'hex'});

I checked double times the chunks.items and then used simple hex oddless value as @JJ Geewax mentioned and found that the problem in my case was in interaction between node fs module and Buffer.

To get it working I've changed from passing a raw Buffer into string with right encoding:

...
fs.writeFileSync(resultFilePath, resultBuffer.toString('hex'), {encoding: 'hex'});

Maybe someone found this useful.

Upvotes: 0

JJ Geewax
JJ Geewax

Reputation: 10579

Are you sure the length of your string is even? Buffer raises that (unclear) error message when the hex string you're providing is odd (len % 2 != 0) rather than the required even.

A good test would be to log the hex string you have, and then try it in 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

I've opened a pull-request on GitHub to fix the error message to be a bit more clear: https://github.com/nodejs/node/pull/4877/files

Upvotes: 1

Related Questions