將十進制轉為64進制表示。
- 方法一:
將數值整除64方式(缺點:數值大小受限缨睡,超過2**63后會出錯)
public class Base64Util {
public static final int BASE64_RADIX = 64;
public static final int CHAR_SIZE = 20;
final static char[] DIGITS = {
'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', '+', '-',
};
public static String toBase64(long i) {
char[] buf = new char[CHAR_SIZE];
int charPos = CHAR_SIZE - 1;
boolean negative = (i < 0);
if (!negative) {
i = -i;
}
while (i <= -BASE64_RADIX) {
buf[charPos--] = DIGITS[(int) (-(i % BASE64_RADIX))];
i = i / BASE64_RADIX;
}
buf[charPos] = DIGITS[(int) (-i)];
if (negative) {
buf[--charPos] = '-';
}
return new String(buf, charPos, (CHAR_SIZE - charPos));
}
public static void main(String[] args) {
System.out.println(toBase64(4L));
}
}