
生成随机字符串
HashUtil.java
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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
@UtilityClass
public class HashUtil {
/** The logger. */
private static final Logger LOGGER = LoggerFactory.getLogger(HashUtil.class);
private static final String baseDigits = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
private static final int BASE = baseDigits.length();
private static final char[] digitsChar = baseDigits.toCharArray();
private static final int FAST_SIZE = 'z';//122
private static final int[] digitsIndex = new int[FAST_SIZE + 1];
static {
for (int i = 0; i < FAST_SIZE; i++) {
digitsIndex[i] = -1;
}
//把每个字符对应的位置放入数组
for (int i = 0; i < BASE; i++) {
digitsIndex[digitsChar[i]] = i;
}
}
private static long decode(String s) {
long result = 0L;
long multiplier = 1;
for (int pos = s.length() - 1; pos >= 0; pos--) {
int index = getIndex(s, pos);
result += (index * multiplier);
multiplier <<= 6;
}
return result;
}
private static String base62(long number) {
if (number < 0)
LOGGER.error("Number(Base62) must be positive: " + number);
if (number == 0)
return "0";
StringBuilder buf = new StringBuilder();
while (number != 0) {
buf.append(digitsChar[(int) (number % BASE)]);
// buf.append(digitsChar[(int) (number & (BASE - 1))]);
number /= BASE;
// number >>>= 6;
}
return buf.reverse().toString();
}
/**
*
* @param number
* @param shift
* @return
*/
private static String hex10To64(long number, int shift) {
char[] buf = new char[64];
int charPos = 64;
int radix = 1 << shift;
long mask = radix - 1;
do {
buf[--charPos] = digitsChar[(int)(number & mask)];
number >>>= shift;
} while (number != 0);
return new String(buf, charPos, (64 - charPos));
}
public static String base62(long number, int length) {
char[] buf = new char[length];
do {
buf[--length] = digitsChar[(int) (number % BASE)];
number /= BASE;
} while (number != 0);
for (int i = 0; i < length; i++) buf[i] = '0';
return new String(buf);
}
private static int getIndex(String s, int pos) {
char c = s.charAt(pos);
if (c > FAST_SIZE) {
LOGGER.error("Unknow character for Base64: " + s);
}
int index = digitsIndex[c];
if (index == -1) {
LOGGER.error("Unknow character for Base64: " + s);
}
return index;
}
}
工具类
Tutil.java
1
2
3
4
5
6
7
8
9
10
11
/**
* id generator for current project
*
* <p> ID format: 7 digits time prefix(until 2081), 5 digits random alpha number.
* ID repetition probability per millisecond is 1/916,132,832
*
* @return 12 digits ID
*/
public static String id() {
return HashUtil.base62(System.currentTimeMillis(),7) + HashUtil.base62(System.nanoTime() & 0x1FFFFFFF,5);
}




近期评论