简单的BASE64实现

由于时间问题还没有全部实现,先备忘一下。

java 代码
  1. public class Base64Trs {   
  2.   
  3.     public static final char[] base64_alphabet = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',   
  4.             'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 
  5.             'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q',
  6.             'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2',   
  7.             '3', '4', '5', '6', '7', '8', '9', '+', '/', '=' };   
  8.   
  9.     /**  
  10.      * 读取数据3字节用AND取前6位,放入新的变量中右移两位,  
  11.      * 高两位清0AND取第一个字节的后2位和第二个字节的前4位  
  12.      * 移位放入新变量中右移两位,清0……依此类推。  
  13.      *   
  14.      * @param bytes  
  15.      */  
  16.     public static void encode(byte[] bytes) {   
  17.   
  18.         int len = (int) Math.ceil(bytes.length / 3) + 1//按照3个字符进行分组的分组数   
  19.         int[] buf = new int[4];   
  20.         byte[] temp = new byte[3];   
  21.         p(len);   
  22.         for (int i = 0; i < len; i++) {   
  23.             int base = i * 3;   
  24.             //需要处理补全字符 ==   
  25.             for (int j = 0; j < 3; j++) {   
  26.                 if (i == len - 1 && base + j > bytes.length - 1) {   
  27.                     temp[j] = (byte0x00;   
  28.                 } else {   
  29.                     temp[j] = bytes[base + j];   
  30.                 }   
  31.             }   
  32.             buf[0] = (((int) temp[0]) >>> 2);   
  33.             buf[1] = ((temp[0] & 0x03) << 4 | (((int) temp[1]) >>> 4));   
  34.             buf[2] = ((temp[1] & 0x0f) << 2 | (((int) temp[2]) >>> 6));   
  35.             buf[3] = (temp[2] & 0x3f);   
  36.             for (int j = 0; j < 4; j++) {   
  37.                 p(base64_alphabet[buf[j]] + "");   
  38.             }   
  39.         }   
  40.   
  41.     }   
  42.   
  43.     public static void main(String[] args) {   
  44.         String s = "cccc";   
  45.         Base64Trs.encode(s.getBytes());   
  46.         System.out.println(Base64Util.encode(s));   
  47.     }   
  48.   
  49.     private static void p(String s) {   
  50.         System.out.println(s);   
  51.     }   
  52.   
  53.     private static void p(int s) {   
  54.         System.out.println(s);   
  55.     }   
  56. }   
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值