public static StringBuffer encode ( byte [ ] data ) { int rem = data . length % 3 ; int num = data . length / 3 ; StringBuffer result = new StringBuffer ( ) ; int p = 0 ; // int c=0; for ( int i = 0 ; i < num ; i ++ ) { int b1 = ( data [ p ] & 0xfc ) >> 2 ; int b2 = ( data [ p ] & 0x03 ) << 4 | ( data [ p + 1 ] & 0xf0 ) >> 4 ; int b3 = ( data [ p + 1 ] & 0x0f ) << 2 | ( data [ p + 2 ] & 0xc0 ) >> 6 ; int b4 = data [ p + 2 ] & 0x3f ; result . append ( b64encode ( b1 ) ) ; result . append ( b64encode ( b2 ) ) ; result . append ( b64encode ( b3 ) ) ; result . append ( b64encode ( b4 ) ) ; p += 3 ; // c += 4; } switch ( rem ) { case 0 : break ; case 1 : { int b1 = ( data [ p ] & 0xfc ) >> 2 ; int b2 = ( data [ p ] & 0x03 ) << 4 ; result . append ( b64encode ( b1 ) ) ; result . append ( b64encode ( b2 ) ) ; result . append ( ' ' ) ; result . append ( ' ' ) ; break ; } case 2 : { int b1 = ( data [ p ] & 0xfc ) >> 2 ; int b2 = ( data [ p ] & 0x03 ) << 4 | ( data [ p + 1 ] & 0xf0 ) >> 4 ; int b3 = ( data [ p + 1 ] & 0x0f ) << 2 ; result . append ( b64encode ( b1 ) ) ; result . append ( b64encode ( b2 ) ) ; result . append ( b64encode ( b3 ) ) ; result . append ( ' ' ) ; break ; } } return result ; }
Base64 encode a byte array .