public static String base64Encode ( byte [ ] bytes ) { // always sequence of 4 characters for each 3 bytes; padded with '='s as necessary: StringBuilder buf = new StringBuilder ( ( ( bytes . length + 2 ) / 3 ) * 4 ) ; // first, handle complete chunks (fast loop) int i = 0 ; for ( int end = bytes . length - 2 ; i < end ; ) { int chunk = ( ( bytes [ i ++ ] & 0xFF ) << 16 ) | ( ( bytes [ i ++ ] & 0xFF ) << 8 ) | ( bytes [ i ++ ] & 0xFF ) ; buf . append ( lookup [ chunk >> 18 ] ) ; buf . append ( lookup [ ( chunk >> 12 ) & 0x3F ] ) ; buf . append ( lookup [ ( chunk >> 6 ) & 0x3F ] ) ; buf . append ( lookup [ chunk & 0x3F ] ) ; } // then leftovers, if any int len = bytes . length ; if ( i < len ) { // 1 or 2 extra bytes? int chunk = ( ( bytes [ i ++ ] & 0xFF ) << 16 ) ; buf . append ( lookup [ chunk >> 18 ] ) ; if ( i < len ) { // 2 bytes chunk |= ( ( bytes [ i ] & 0xFF ) << 8 ) ; buf . append ( lookup [ ( chunk >> 12 ) & 0x3F ] ) ; buf . append ( lookup [ ( chunk >> 6 ) & 0x3F ] ) ; } else { // 1 byte buf . append ( lookup [ ( chunk >> 12 ) & 0x3F ] ) ; buf . append ( ' ' ) ; } buf . append ( ' ' ) ; } return buf . toString ( ) ; }
Encodes the specified data into a base64 string .