Base62Util.java
2.26 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
package com.sitech.util;
import java.math.BigInteger;
import java.util.UUID;
/**
*
* @author liujhc <liujhc@si-tech.com.cn>
*/
public class Base62Util {
private static final String ALPHABET = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
private static final BigInteger divisor = BigInteger.valueOf(ALPHABET.length());
public static String encode(BigInteger integer) {
BigInteger bi = integer.shiftLeft(1);
if (bi.signum() == -1) {//如果是负数,变为正数加1
bi = bi.negate().add(BigInteger.ONE);
}
StringBuilder sb = new StringBuilder();
while (bi.signum() != 0) {
BigInteger[] arr = bi.divideAndRemainder(divisor);
bi = arr[0];
sb.append(ALPHABET.charAt(arr[1].intValue()));
}
return sb.reverse().toString();
}
public static BigInteger decodeToInteger(String str) {
BigInteger bi = BigInteger.ZERO;
int len = str.length();
for (int i = 0; i < len; i++) {
String v = String.valueOf(ALPHABET.indexOf(str.charAt(len - 1 - i)));
bi = new BigInteger(v).multiply(divisor.pow(i)).add(bi);
}
if (bi.getLowestSetBit() == 0) {
bi = bi.subtract(BigInteger.ONE).negate();
}
return bi.shiftRight(1);
}
public static String encode(byte[] bytes) {
return encode(new BigInteger(bytes));
}
public static String encode(long num) {
return encode(BigInteger.valueOf(num));
}
public static byte[] decodeToBytes(String str) {
return decodeToInteger(str).toByteArray();
}
/**
* 通过此方法生成的随机UUID只有22位长
*
* @return
*/
public static String encodeUUID(UUID uuid) {
long msb = uuid.getMostSignificantBits(), lsb = uuid.getLeastSignificantBits();
return encode(BigInteger.valueOf(msb).shiftLeft(64).add(BigInteger.valueOf(lsb)));
}
/**
* 通过此方法生成的随机UUID只有22位长
*
* @return
*/
public static UUID decodeToUUID(String base62tr) {
BigInteger bi = decodeToInteger(base62tr);
long lsb = bi.longValue();
long msb = bi.shiftRight(64).longValue();
return new UUID(msb, lsb);
}
}