Error: Invalid hexadecimal 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 the console, lay out

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

Are you sure your string is even? The buffer raises this (obscure) error message when the hexadecimal string you provide is odd ( len % 2 != 0), and not required.

A good test would be to register the sixth line you have, and then try 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 opened a GitHub download request to fix the error message, to be more clear: https://github.com/nodejs/node/pull/4877/files

+1
source

io.js, 1.2.

, , :

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

chunks.items , @JJ Geewax, , fs .

, :

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

, - .

0

Source: https://habr.com/ru/post/1528965/


All Articles