public
Last active

Base64 encode and decode in javascript

  • Download Gist
base64.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
var Base64 = {
characters: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=" ,
 
encode: function( string )
{
var characters = Base64.characters;
var result = '';
 
var i = 0;
do {
var a = string.charCodeAt(i++);
var b = string.charCodeAt(i++);
var c = string.charCodeAt(i++);
 
a = a ? a : 0;
b = b ? b : 0;
c = c ? c : 0;
 
var b1 = ( a >> 2 ) & 0x3F;
var b2 = ( ( a & 0x3 ) << 4 ) | ( ( b >> 4 ) & 0xF );
var b3 = ( ( b & 0xF ) << 2 ) | ( ( c >> 6 ) & 0x3 );
var b4 = c & 0x3F;
 
if( ! b ) {
b3 = b4 = 64;
} else if( ! c ) {
b4 = 64;
}
 
result += Base64.characters.charAt( b1 ) + Base64.characters.charAt( b2 ) + Base64.characters.charAt( b3 ) + Base64.characters.charAt( b4 );
 
} while ( i < string.length );
 
return result;
} ,
 
decode: function( string )
{
var characters = Base64.characters;
var result = '';
 
var i = 0;
do {
var b1 = Base64.characters.indexOf( string.charAt(i++) );
var b2 = Base64.characters.indexOf( string.charAt(i++) );
var b3 = Base64.characters.indexOf( string.charAt(i++) );
var b4 = Base64.characters.indexOf( string.charAt(i++) );
 
var a = ( ( b1 & 0x3F ) << 2 ) | ( ( b2 >> 4 ) & 0x3 );
var b = ( ( b2 & 0xF ) << 4 ) | ( ( b3 >> 2 ) & 0xF );
var c = ( ( b3 & 0x3 ) << 6 ) | ( b4 & 0x3F );
 
result += String.fromCharCode(a) + (b?String.fromCharCode(b):'') + (c?String.fromCharCode(c):'');
 
} while( i < string.length );
 
return result;
}
};

if( ! b ) {
b3 = b4 = 64;
}
????
String.fromCharCode(0) ???

@Yaffle: I know there is a question formulated in there somewhere but I can not seem to find it ;-)

@yahiko,
this algorithm returns wrong result on the following tests:

alert(Base64.encode(''));
alert(window.btoa(''));
alert(Base64.encode('a' + String.fromCharCode(0)));
alert(window.btoa('a' + String.fromCharCode(0)));

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.