Skip to content

Instantly share code, notes, and snippets.

@orvn
Created February 5, 2024 23:26
Show Gist options
  • Save orvn/d6a8c4c251989568338c9433cb0b32b4 to your computer and use it in GitHub Desktop.
Save orvn/d6a8c4c251989568338c9433cb0b32b4 to your computer and use it in GitHub Desktop.
A converter for text to hexadecimel, and back to text (supports all unicode characters). Useful for places where base64 isn't usable, or doesn't support non-ascii characters.
function strToHex(str) {
return Array.from(str).map(char =>
char.codePointAt(0).toString(16).padStart(4, '0')
).join('');
}
function hexToStr(hex) {
let result = '';
for (let i = 0; i < hex.length; i += 4) {
result += String.fromCharCode(parseInt(hex.substring(i, i + 4), 16));
}
return result;
}
const hexed = strToHex("Łørem Ipsüм");
console.log(hexed);
const dehexed = hexToStr(hexed);
console.log(dehexed);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment