Skip to content

Instantly share code, notes, and snippets.

@arextar
Created November 12, 2011 00:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save arextar/1359816 to your computer and use it in GitHub Desktop.
Save arextar/1359816 to your computer and use it in GitHub Desktop.
Encode into Base64
function btoa(
a, //String to encode
b, //Array of Base64 characters
c,d,e,f,g,x //Placeholder
){
for(d=a.length, //Set d to the input's length
e="charCodeAt", //Shortcut for String.charCodeAt
f=-[,2,1][d%3], //Get how many equal signs need to be added to the end
x=0; //Initiate iteration variable
x<d; //Continue loop until x exceeds the length of the input
)
g=a[e](x++)<<16|a[e](x++)<<8|a[e](x++), //Create a binary buffer of the three characters at x, while incrementing x by 3
c=[c]+b[g>>18&63]+b[g>>12&63]+b[g>>6&63]+b[g&63]; //Push the 4 characters described by that buffer to the returned buffer
return f?c.slice(0,f)+(~f?"==":"="):c;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment