Created
August 21, 2022 00:52
-
-
Save ygkn/a5c9ad0dd4443261e4032b204f9ff7a3 to your computer and use it in GitHub Desktop.
Hex and Base64 interop in TypeScript
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
const hexToBase64 = (hex: string) => | |
btoa( | |
String.fromCharCode( | |
...(hex.match(/[0-9a-f]{2}/gi) ?? []).map((c) => parseInt(c, 16)) | |
) | |
); | |
const base64ToHex = (base64: string) => | |
[...atob(base64)] | |
.map((c) => c.charCodeAt(0).toString(16).padStart(2, "0")) | |
.join(""); | |
/** | |
* test 1 | |
*/ | |
{ | |
const base46Str = "B9PlPiWDr2Ve2EpZVvBL"; | |
console.log(base64ToHex(base46Str)); | |
console.assert(hexToBase64(base64ToHex(base46Str)) === base46Str); | |
} | |
/** | |
* test 2 | |
*/ | |
{ | |
const hexString = "a0eebc999c0b4ef8bb6d6bb9bd380a11"; | |
console.log(hexToBase64(hexString)); | |
console.assert(base64ToHex(hexToBase64(hexString)) === hexString); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment