由于时间问题还没有全部实现,先备忘一下。
java 代码
- public class Base64Trs {
- public static final char[] base64_alphabet = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',
- 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b',
- 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q',
- 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2',
- '3', '4', '5', '6', '7', '8', '9', '+', '/', '=' };
- /**
- * 读取数据3字节用AND取前6位,放入新的变量中右移两位,
- * 高两位清0AND取第一个字节的后2位和第二个字节的前4位
- * 移位放入新变量中右移两位,清0……依此类推。
- *
- * @param bytes
- */
- public static void encode(byte[] bytes) {
- int len = (int) Math.ceil(bytes.length / 3) + 1; //按照3个字符进行分组的分组数
- int[] buf = new int[4];
- byte[] temp = new byte[3];
- p(len);
- for (int i = 0; i < len; i++) {
- int base = i * 3;
- //需要处理补全字符 ==
- for (int j = 0; j < 3; j++) {
- if (i == len - 1 && base + j > bytes.length - 1) {
- temp[j] = (byte) 0x00;
- } else {
- temp[j] = bytes[base + j];
- }
- }
- buf[0] = (((int) temp[0]) >>> 2);
- buf[1] = ((temp[0] & 0x03) << 4 | (((int) temp[1]) >>> 4));
- buf[2] = ((temp[1] & 0x0f) << 2 | (((int) temp[2]) >>> 6));
- buf[3] = (temp[2] & 0x3f);
- for (int j = 0; j < 4; j++) {
- p(base64_alphabet[buf[j]] + "");
- }
- }
- }
- public static void main(String[] args) {
- String s = "cccc";
- Base64Trs.encode(s.getBytes());
- System.out.println(Base64Util.encode(s));
- }
- private static void p(String s) {
- System.out.println(s);
- }
- private static void p(int s) {
- System.out.println(s);
- }
- }