user4735397
user4735397

Reputation:

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)

Upvotes: 1

Views: 8576

Answers (1)

mscdex
mscdex

Reputation: 106746

If you have a Buffer, you can call toString() directly and pass the kind of output you want, for example: decryptedPayload.toString('hex')

Upvotes: 5

Related Questions