Skip to content

Instantly share code, notes, and snippets.

@valentinkostadinov
Created June 27, 2013 10:29
Show Gist options
  • Select an option

  • Save valentinkostadinov/5875467 to your computer and use it in GitHub Desktop.

Select an option

Save valentinkostadinov/5875467 to your computer and use it in GitHub Desktop.
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))
}
@jonlepage

Copy link
Copy Markdown

awesome thanks a lot friend

@yegannezhad

Copy link
Copy Markdown

nice

@A-312

A-312 commented Jun 8, 2020

Copy link
Copy Markdown

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

@togoenvogue

Copy link
Copy Markdown

You are a life saver. I just needed to tweak your code to get what I have been looking for since 5 hours.
I needed to get 00480065006c006c006f instead of 48656c6c6f by converting the word Hello to utf-16
Thank you again

@Rudxain

Rudxain commented Jul 15, 2022

Copy link
Copy Markdown

I wonder why nobody has made a @tc39 proposal to standardize and include this in JS. It's funny that JS has atob & btoa but hex processing can only be done on Numbers in vanilla JS.

Edit: atob and btoa aren't part of ES, so they don't count

@MGF15

MGF15 commented Nov 19, 2022

Copy link
Copy Markdown
> h = 'hello 🤣';
'hello 🤣'
> const encoded = Buffer.from(h).toString('hex');
undefined
> encoded
'68656c6c6f20f09fa4a3'
> Buffer.from(encoded, 'hex').toString();
'hello 🤣'
> 

@Rudxain

Rudxain commented Nov 19, 2022

Copy link
Copy Markdown

@MGF15 that's only possible in NodeJS, this Gist is portable

Actually, this Gist is also not portable between environments. My bad

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment