提交 | 用户 | age | ||
826b66 | 1 | package com.hx.util; |
C | 2 | |
3 | /** | |
4 | * Base64 工具类 | |
5 | */ | |
6 | public class Base64Util { | |
7 | private static final char last2byte = (char) Integer.parseInt("00000011", 2); | |
8 | private static final char last4byte = (char) Integer.parseInt("00001111", 2); | |
9 | private static final char last6byte = (char) Integer.parseInt("00111111", 2); | |
10 | private static final char lead6byte = (char) Integer.parseInt("11111100", 2); | |
11 | private static final char lead4byte = (char) Integer.parseInt("11110000", 2); | |
12 | private static final char lead2byte = (char) Integer.parseInt("11000000", 2); | |
13 | private static final char[] encodeTable = new char[]{'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', '+', '/'}; | |
14 | ||
15 | public Base64Util() { | |
16 | } | |
17 | ||
18 | public static String encode(byte[] from) { | |
19 | StringBuilder to = new StringBuilder((int) ((double) from.length * 1.34D) + 3); | |
20 | int num = 0; | |
21 | char currentByte = 0; | |
22 | ||
23 | int i; | |
24 | for (i = 0; i < from.length; ++i) { | |
25 | for (num %= 8; num < 8; num += 6) { | |
26 | switch (num) { | |
27 | case 0: | |
28 | currentByte = (char) (from[i] & lead6byte); | |
29 | currentByte = (char) (currentByte >>> 2); | |
30 | case 1: | |
31 | case 3: | |
32 | case 5: | |
33 | default: | |
34 | break; | |
35 | case 2: | |
36 | currentByte = (char) (from[i] & last6byte); | |
37 | break; | |
38 | case 4: | |
39 | currentByte = (char) (from[i] & last4byte); | |
40 | currentByte = (char) (currentByte << 2); | |
41 | if (i + 1 < from.length) { | |
42 | currentByte = (char) (currentByte | (from[i + 1] & lead2byte) >>> 6); | |
43 | } | |
44 | break; | |
45 | case 6: | |
46 | currentByte = (char) (from[i] & last2byte); | |
47 | currentByte = (char) (currentByte << 4); | |
48 | if (i + 1 < from.length) { | |
49 | currentByte = (char) (currentByte | (from[i + 1] & lead4byte) >>> 4); | |
50 | } | |
51 | } | |
52 | ||
53 | to.append(encodeTable[currentByte]); | |
54 | } | |
55 | } | |
56 | ||
57 | if (to.length() % 4 != 0) { | |
58 | for (i = 4 - to.length() % 4; i > 0; --i) { | |
59 | to.append("="); | |
60 | } | |
61 | } | |
62 | ||
63 | return to.toString(); | |
64 | } | |
65 | } |