public class BASE64Encoder { 6 7 private static char[] codec_table = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 8 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 9 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 10 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 11 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', 12 '7', '8', '9', '+', '/' }; 13 14 public BASE64Encoder() { 15 16 } 17 18 public String encode(byte[] a) { 19 int totalBits = a.length * 8; 20 int nn = totalBits % 6; 21 int curPos = 0;// process bits 22 StringBuffer toReturn = new StringBuffer(); 23 while (curPos < totalBits) { 24 int bytePos = curPos / 8; 25 switch (curPos % 8) { 26 case 0: 27 toReturn.append(codec_table[(a[bytePos] & 0xfc) >> 2]); 28 break; 29 case 2: 30 31 toReturn.append(codec_table[(a[bytePos] & 0x3f)]); 32 break; 33 case 4: 34 if (bytePos == a.length - 1) { 35 toReturn 36 .append(codec_table[((a[bytePos] & 0x0f) << 2) & 0x3f]); 37 } else { 38 int pos = (((a[bytePos] & 0x0f) << 2) | ((a[bytePos + 1] & 0xc0) >> 6)) & 0x3f; 39 toReturn.append(codec_table[pos]); 40 } 41 break; 42 case 6: 43 if (bytePos == a.length - 1) { 44 toReturn 45 .append(codec_table[((a[bytePos] & 0x03) << 4) & 0x3f]); 46 } else { 47 int pos = (((a[bytePos] & 0x03) << 4) | ((a[bytePos + 1] & 0xf0) >> 4)) & 0x3f; 48 toReturn.append(codec_table[pos]); 49 } 50 break; 51 default: 52 //never hanppen 53 break; 54 } 55 curPos+=6; 56 } 57 if(nn==2) 58 { 59 toReturn.append("=="); 60 } 61 else if(nn==4) 62 { 63 toReturn.append("="); 64 } 65 return toReturn.toString(); 66 67 } 68 69 }
这样运行一个测试程序
1 public static void main(String[] args) throws Exception { 2 3 4 BASE64Encoder encoder=new BASE64Encoder(); 5 sun.misc.BASE64Encoder sunEncoder=new sun.misc.BASE64Encoder(); 6 byte[] testBytes=new byte[1024*1024*2]; 7 long start=System.currentTimeMillis(); 8 for(int i=0;i<10;i++) 9 { 10 sunEncoder.encode(testBytes); 11 } 12 13 System.out.println("[sun encoder]use time :"+(System.currentTimeMillis()-start)); 14 start=System.currentTimeMillis(); 15 for(int i=0;i<10;i++) 16 { 17 encoder.encode(testBytes); 18 } 19 20 System.out.println("[our encoder]use time :"+(System.currentTimeMillis()-start)); 21 22 }
出来的结果是:
[sun encoder]use time :4844
[our encoder]use time :2609
差不多慢一倍。