Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
JavaScript HEX encoding
function toHex(s) {
// utf8 to latin1
var s = unescape(encodeURIComponent(s))
var h = ''
for (var i = 0; i < s.length; i++) {
h += s.charCodeAt(i).toString(16)
}
return h
}
function fromHex(h) {
var s = ''
for (var i = 0; i < h.length; i+=2) {
s += String.fromCharCode(parseInt(h.substr(i, 2), 16))
}
return decodeURIComponent(escape(s))
}
@djmisterjon

This comment has been minimized.

Copy link

djmisterjon commented Sep 26, 2017

awesome thanks a lot friend

@yegannezhad

This comment has been minimized.

Copy link

yegannezhad commented Mar 7, 2019

nice

@A-312

This comment has been minimized.

Copy link

A-312 commented Jun 8, 2020

A better way is to use %20 format, like that:

function toHex(s) {
    let h = ''
    for (let i = s.length - 1; i >= 0; i--)
        h = '%'+ s.charCodeAt(i).toString(16) + h
    return h
}

toHex('test') // "%74%65%73%74"
decodeURIComponent('%74%65%73%74') // test
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.