2014-02-26 82 views
4

這裏是我的節點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; 
} 

這裏是十六進制串值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); 
+0

'new Buffer()'將第二個參數作爲消息的編碼。通過編碼它是指字符編碼(默認爲'utf8'),而不是數字編碼。 –

+0

@ThalisK。 'hex'是使用'Buffer'的有效編碼('base64'是另一個)。 @ coure2011考慮到'dataObj.len'是'05',並且您顯示的值不包含該值,您確定msg是正確的嗎? – robertklep

+0

是的,這是正確的...這個len沒有顯示整個消息的長度,但它的目的是不同的。 – coure2011

回答

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上拉請求修正錯誤消息是有點更清楚:https://github.com/nodejs/node/pull/4877/files

相關問題