fork download
  1. class MyBase64 {
  2.  
  3. private final static char[] ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".toCharArray();
  4.  
  5. private static int[] toInt = new int[128];
  6.  
  7. static {
  8. for(int i=0; i< ALPHABET.length; i++){
  9. toInt[ALPHABET[i]]= i;
  10. }
  11. }
  12.  
  13. /**
  14. * Translates the specified byte array into Base64 string.
  15. *
  16. * @param buf the byte array (not null)
  17. * @return the translated Base64 string (not null)
  18. */
  19. public static String encode(byte[] buf){
  20. int size = buf.length;
  21. char[] ar = new char[((size + 2) / 3) * 4];
  22. int a = 0;
  23. int i=0;
  24. while(i < size){
  25. byte b0 = buf[i++];
  26. byte b1 = (i < size) ? buf[i++] : 0;
  27. byte b2 = (i < size) ? buf[i++] : 0;
  28.  
  29. int mask = 0x3F;
  30. ar[a++] = ALPHABET[(b0 >> 2) & mask];
  31. ar[a++] = ALPHABET[((b0 << 4) | ((b1 & 0xFF) >> 4)) & mask];
  32. ar[a++] = ALPHABET[((b1 << 2) | ((b2 & 0xFF) >> 6)) & mask];
  33. ar[a++] = ALPHABET[b2 & mask];
  34. }
  35. switch(size % 3){
  36. case 1: ar[--a] = '=';
  37. case 2: ar[--a] = '=';
  38. }
  39. return new String(ar);
  40. }
  41.  
  42. /**
  43. * Translates the specified Base64 string into a byte array.
  44. *
  45. * @param s the Base64 string (not null)
  46. * @return the byte array (not null)
  47. */
  48. public static byte[] decode(String s){
  49. int delta = s.endsWith( "==" ) ? 2 : s.endsWith( "=" ) ? 1 : 0;
  50. byte[] buffer = new byte[s.length()*3/4 - delta];
  51. int mask = 0xFF;
  52. int index = 0;
  53. for(int i=0; i< s.length(); i+=4){
  54. int c0 = toInt[s.charAt( i )];
  55. int c1 = toInt[s.charAt( i + 1)];
  56. buffer[index++]= (byte)(((c0 << 2) | (c1 >> 4)) & mask);
  57. if(index >= buffer.length){
  58. return buffer;
  59. }
  60. int c2 = toInt[s.charAt( i + 2)];
  61. buffer[index++]= (byte)(((c1 << 4) | (c2 >> 2)) & mask);
  62. if(index >= buffer.length){
  63. return buffer;
  64. }
  65. int c3 = toInt[s.charAt( i + 3 )];
  66. buffer[index++]= (byte)(((c2 << 6) | c3) & mask);
  67. }
  68. return buffer;
  69. }
  70.  
  71. }
  72.  
Runtime error #stdin #stdout 0.09s 212736KB
stdin
Standard input is empty
stdout
Standard output is empty