简体   繁体   中英

converting string into hex in js

im using node.js and I have a string that I am trying to convert into hex.

This is the function I'm using:

function toHex(str) {
    var hex = '';
    var i = 0;
    while(str.length > i) {
        hex += ''+str.charCodeAt(i).toString(16);
        i++;
    }
    return hex;
} 

And this is how I am trying to call it:

console.log('Payload: ' + toHex(decryptedPayload));

However when it runs I get this error:

  hex += ''+str.charCodeAt(i).toString(16); ^ TypeError: undefined is not a function at toHex (C:\\Users\\Office\\Desktop\\luigi-master\\lib\\middleware.js:131:17) at Middleware._transform (C:\\Users\\Office\\Desktop\\luigi-master\\lib\\middleware.js:161:29) at Middleware.Transform._read (_stream_transform.js:179:10) at Middleware.Transform._write (_stream_transform.js:167:12) at doWrite (_stream_writable.js:301:12) at writeOrBuffer (_stream_writable.js:288:5) at Middleware.Writable.write (_stream_writable.js:217:11) at Packetize.ondata (_stream_readable.js:540:20) at Packetize.emit (events.js:107:17) at readableAddChunk (_stream_readable.js:163:16) 

如果你有一个Buffer,你可以直接调用toString()并传递你想要的那种输出,例如: decryptedPayload.toString('hex')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM