将原始数据编码为base64编码

public class Base64 {
        
   static private char[] alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".toCharArray();
         /** 
    * 将原始数据编码为base64编码 
    */   
   static public String encode(String str)    
    {    
           byte[] data = str.getBytes();
       char[] out = new char[((data.length + 2) / 3) * 4];    
  
       for (int i = 0, index = 0; i < data.length; i += 3, index += 4)    
        {    
               boolean quad = false;    
               boolean trip = false;    
               int val = (0xFF & (int) data[i]);    
                val <<= 8;    
               if ((i + 1) < data.length)    
                {    
                        val |= (0xFF & (int) data[i + 1]);    
                        trip = true;    
                }    
                val <<= 8;    
               if ((i + 2) < data.length)    
                {    
                        val |= (0xFF & (int) data[i + 2]);    
                        quad = true;    
                }    
                out[index + 3] = alphabet[(quad ? (val & 0x3F) : 64)];    
                val >>= 6;    
                out[index + 2] = alphabet[(trip ? (val & 0x3F) : 64)];    
                val >>= 6;    
                out[index + 1] = alphabet[val & 0x3F];    
                val >>= 6;    
                out[index + 0] = alphabet[val & 0x3F];    
        }    
       return new String(out);    
    }    


来自lordhong
永久域名 http://lordhong.iteye.com
的javaeye客户端开源项目源代码中

你可能感兴趣的:(base64)