public static String encode ( final Byte [ ] data ) { final StringBuilder builder = new StringBuilder ( ) ; final int dataRemainder = data . length % 3 ; int j = 0 ; int n = 0 ; for ( ; j < data . length ; j += 3 ) { if ( j < data . length - dataRemainder ) { n = ( ( data [ j ] & 0xFF ) << 16 ) + ( ( data [ j + 1 ] & 0xFF ) << 8 ) + ( data [ j + 2 ] & 0xFF ) ; } else { if ( dataRemainder == 1 ) { n = ( data [ j ] & 0xFF ) << 16 ; } else if ( dataRemainder == 2 ) { n = ( ( data [ j ] & 0xFF ) << 16 ) + ( ( data [ j + 1 ] & 0xFF ) << 8 ) ; } } // Left here for readability // byte char1 = (byte) ((n >>> 18) & 0x3F); // byte char2 = (byte) ((n >>> 12) & 0x3F); // byte char3 = (byte) ((n >>> 6) & 0x3F); // byte char4 = (byte) (n & 0x3F); builder . append ( BASE_64_CHARS . charAt ( ( byte ) ( ( n >>> 18 ) & 0x3F ) ) ) ; builder . append ( BASE_64_CHARS . charAt ( ( byte ) ( ( n >>> 12 ) & 0x3F ) ) ) ; builder . append ( BASE_64_CHARS . charAt ( ( byte ) ( ( n >>> 6 ) & 0x3F ) ) ) ; builder . append ( BASE_64_CHARS . charAt ( ( byte ) ( n & 0x3F ) ) ) ; } final int bLength = builder . length ( ) ; // append '=' to pad if ( data . length % 3 == 1 ) { builder . replace ( bLength - 2 , bLength , "==" ) ; } else if ( data . length % 3 == 2 ) { builder . replace ( bLength - 1 , bLength , "=" ) ; } return builder . toString ( ) ; }
Encodes a byte array as a Base64 string .