Created
August 10, 2017 16:18
-
-
Save snshn/9d553d77508a7b0046ac79bad8254a6b to your computer and use it in GitHub Desktop.
Kind of like btoa/atob, but doesn't trip on Unicode.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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