Skip to content

Instantly share code, notes, and snippets.

@ergoithz
Created May 6, 2014 11:05
Show Gist options
  • Save ergoithz/f821ebd6af0daf81162d to your computer and use it in GitHub Desktop.
Save ergoithz/f821ebd6af0daf81162d to your computer and use it in GitHub Desktop.
Simpler JS hex serialization
/* Damn simple hex parser, with utf8 convenience functions */
var utf8={
decode: function(s){
return decodeURIComponent(escape(s));
},
encode: function(s){
return unescape(encodeURIComponent(s));
}
},
hex={
decode: function(str){
var r='', i=0, l=str.length;
while(i<l)
r += String.fromCharCode(parseInt(str.substring(i, i+=2), 16));
return r;
},
encode: function(str){
var r='', i=0, l=str.length;
while(i<l) r += str.charCodeAt(i++).toString(16);
if(r.length>l*2) // raise on multibyte characters
throw 'Invalid input, only byte strings are allowed.';
return r;
},
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment