Last active
September 13, 2024 04:11
-
-
Save GeorgioWan/16a7ad2a255e8d5c7ed1aca3ab4aacec to your computer and use it in GitHub Desktop.
Hex & Base64 Encode Decode
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
// Hex to Base64 | |
function hexToBase64(str) { | |
return btoa(String.fromCharCode.apply(null, | |
str.replace(/\r|\n/g, "").replace(/([\da-fA-F]{2}) ?/g, "0x$1 ").replace(/ +$/, "").split(" ")) | |
); | |
} | |
// Base64 to Hex | |
function base64ToHex(str) { | |
for (var i = 0, bin = atob(str.replace(/[ \r\n]+$/, "")), hex = []; i < bin.length; ++i) { | |
let tmp = bin.charCodeAt(i).toString(16); | |
if (tmp.length === 1) tmp = "0" + tmp; | |
hex[hex.length] = tmp; | |
} | |
return hex.join(" "); | |
} | |
// Demo | |
let data = 'E6FF00F0'; | |
let d1 = hexToBase64( data ); | |
console.log(d1); | |
// output: '5v8A8A==' | |
let d2 = base64ToHex( d1 ); | |
console.log(d2.toUpperCase()); | |
// output: 'E6 FF 00 F0' |
Author
GeorgioWan
commented
Sep 5, 2017
Simplier for more strict input
// hex to base64
(source => btoa(
String.fromCharCode(
...source
.match(/.{2}/g)
.map(c => parseInt(c, 16))
)
))("E6FF00F0")
// base64 to hex
(source => Array.prototype.reduce.call(
atob(source),
(acc, c) => acc + `0${c.charCodeAt(0).toString(16)}`.slice(-2),
""
))("5v8A8A==")
i'm sorry, but a i have to ask.
replace(/([\da-fA-F]{2}) ?/g, "0x$1 "). what is this?
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment