Skip to content

Instantly share code, notes, and snippets.

@zazaulola
Last active April 26, 2022 07:45
Show Gist options
  • Save zazaulola/34407a632d889cad470862a7db7ad3e7 to your computer and use it in GitHub Desktop.
Save zazaulola/34407a632d889cad470862a7db7ad3e7 to your computer and use it in GitHub Desktop.
base64 and TypedArray conversion
function arrayToBase64(array) {
let base64 = '';
const encodings = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
const arrayLength = array.byteLength;
const remainder = arrayLength % 3;
const mainLength = arrayLength - remainder;
let a, b, c, d;
let chunk;
// Main loop deals with bytes in chunks of 3
for (let i = 0; i < mainLength; i = i + 3) {
// Combine the three bytes into a single integer
chunk = (array[i] << 16) | (array[i + 1] << 8) | array[i + 2];
// Use bitmasks to extract 6-bit segments from the triplet
a = (chunk & 16515072) >> 18; // 16515072 = (2^6 - 1) << 18
b = (chunk & 258048) >> 12; // 258048 = (2^6 - 1) << 12
c = (chunk & 4032) >> 6; // 4032 = (2^6 - 1) << 6
d = chunk & 63; // 63 = 2^6 - 1
// Convert the raw binary segments to the appropriate ASCII encoding
base64 += encodings[a] + encodings[b] + encodings[c] + encodings[d];
}
// Deal with the remaining bytes and padding
if (remainder == 1) {
chunk = array[mainLength];
a = (chunk & 252) >> 2; // 252 = (2^6 - 1) << 2
// Set the 4 least significant bits to zero
b = (chunk & 3) << 4; // 3 = 2^2 - 1
base64 += encodings[a] + encodings[b] + '==';
} else if (remainder == 2) {
chunk = (array[mainLength] << 8) | array[mainLength + 1];
a = (chunk & 64512) >> 10; // 64512 = (2^6 - 1) << 10
b = (chunk & 1008) >> 4; // 1008 = (2^6 - 1) << 4
// Set the 2 least significant bits to zero
c = (chunk & 15) << 2; // 15 = 2^4 - 1
base64 += encodings[a] + encodings[b] + encodings[c] + '=';
}
return base64;
}
function decode_base64(s) {
var e={},i,k,v=[],r=”,w=String.fromCharCode;
var n=[[65,91],[97,123],[48,58],[47,48],[43,44]];
for(z in n){for(i=n[z][0];i<n[z][1];i++){v.push(w(i));}}
for(i=0;i<64;i++){e[v[i]]=i;}
for(i=0;i<s.length;i+=72){
var b=0,c,x,l=0,o=s.substring(i,i+72);
for(x=0;x<o.length;x++){
c=e[o.charAt(x)];b=(b<=8){r+=w((b>>>(l-=8))%256);}
}
}
return r;
}
function base64ToArray(string) {
return Uint8Array.from(atob(base64_string), c => c.charCodeAt(0));
}
function arrayToBase64web(buffer) {
return arrayToBase64(buffer).replace(/\+/g, '-').replace(/\//g, '_').replace(/=/g,'.');
}
function base64webToArray(string) {
return base64ToArray(string.replace(/-/g, '+').replace(/_/g, '/'));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment