Skip to content

Instantly share code, notes, and snippets.

@nathanstilwell
Last active December 9, 2016 21:38
Show Gist options
  • Save nathanstilwell/182d3e210ee95e8f4b71c5ae38f20f34 to your computer and use it in GitHub Desktop.
Save nathanstilwell/182d3e210ee95e8f4b71c5ae38f20f34 to your computer and use it in GitHub Desktop.
function stringTohex(string) {
// convert to base64
const base64encoded = btoa(string);
// convert to array
const arr = base64encoded.split('');
// convert to string to char code
const charCodes = arr.map((letter) => letter.charCodeAt());
// convert to hex
const secret = charCodes.map((code) => code.toString(16));
return secret.join(' ');
}
function stringTohexTerse(string) {
return btoa(string).split('').map((a) => a.charCodeAt().toString(16)).join(' ');
}
function hexToString(hex) {
// explode hex to array
const hexArr = hex.split(' ');
// convert to char code
const charCodes = hexArr.map((hex) => parseInt(hex, 16));
// convert to char
const base64String = charCodes.map((code) => String.fromCharCode(code)).join('');
// decode base64
return atob(base64String);
}
function hexToStringTerse(hex) {
return atob(hex.split(' ').map((a) => String.fromCharCode(parseInt(a, 16))).join(''));
}
/**
Example usage:
const url = 'http://nathanstilwell.com';
const hex = stringTohexTerse(url);
const back = hexToString(hex);
console.log( `url: ${url} => hex: ${hex}` );
console.log( `hex: ${hex} => url: ${back}` );
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment