Skip to content

Instantly share code, notes, and snippets.

@peaBerberian
Created April 15, 2022 16:01
Show Gist options
  • Save peaBerberian/854d79e6c8dd2bb0f6269bf8f620e6df to your computer and use it in GitHub Desktop.
Save peaBerberian/854d79e6c8dd2bb0f6269bf8f620e6df to your computer and use it in GitHub Desktop.
const base64abc = [
"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M",
"N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z",
"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m",
"n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z",
"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "+", "/",
];
/**
* Convert an array of bytes into a base64 string.
* @param {Array.<number>|Uint8Array} bytes
* @returns {string}
*/
function bytesToBase64(bytes) {
let result = "";
let i;
const length = bytes.length;
for (i = 2; i < length; i += 3) {
result += base64abc[bytes[i - 2] >> 2];
result += base64abc[((bytes[i - 2] & 0x03) << 4) | (bytes[i - 1] >> 4)];
result += base64abc[((bytes[i - 1] & 0x0F) << 2) | (bytes[i] >> 6)];
result += base64abc[bytes[i] & 0x3F];
}
if (i === length + 1) { // 1 octet yet to write
result += base64abc[bytes[i - 2] >> 2];
result += base64abc[(bytes[i - 2] & 0x03) << 4];
result += "==";
}
if (i === length) { // 2 octets yet to write
result += base64abc[bytes[i - 2] >> 2];
result += base64abc[((bytes[i - 2] & 0x03) << 4) | (bytes[i - 1] >> 4)];
result += base64abc[(bytes[i - 1] & 0x0F) << 2];
result += "=";
}
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment