Skip to content

Instantly share code, notes, and snippets.

@snshn
Created August 10, 2017 16:18
Show Gist options
  • Save snshn/9d553d77508a7b0046ac79bad8254a6b to your computer and use it in GitHub Desktop.
Save snshn/9d553d77508a7b0046ac79bad8254a6b to your computer and use it in GitHub Desktop.
Kind of like btoa/atob, but doesn't trip on Unicode.
/**
* Encode a UTF-16 string as a string of hexadecimal letters
*/
function encodeIntoHex (string) {
var hex;
var hexString = "";
for (var i = 0, ilen = string.length; i < ilen; i++) {
hex = string.charCodeAt(i).toString(16);
hexString += ("000" + hex).slice(-4);
}
return hexString
}
/**
* Decode a string of hexadecimal letters back into a UTF-16 string
*/
function decodeFromHex (hexString) {
var hexes = hexString.match(/.{1,4}/g) || [];
var decodedString = "";
for (var i = 0, ilen = hexes.length; i < ilen; i++) {
decodedString += String.fromCharCode(parseInt(hexes[i], 16));
}
return decodedString;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment