无关风月
2024-07-03 f138375f15c072d10335c20ecec9b35f1da78ee4
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
package com.ruoyi.study.utils;
 
import java.util.Random;
 
/**
 * @author HJL
 * @version 1.0
 * @since 2024-05-21 14:22
 */
public class RandomVxUtil {
 
    /**
     * 最后又重复两个0和1,因为需要凑足数组长度为64
     */
    private static final char[] CH = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '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'};
 
    private static final Random RANDOM = new Random();
 
    /**
     * 生成指定长度的随机字符串
     *
     * @param length 长度
     * @return 随机字符串
     */
    public static String createRandomString(int length) {
        if (length > 0) {
            int index = 0;
            char[] temp = new char[length];
            int num = RANDOM.nextInt();
            for (int i = 0; i < length % 5; i++) {
                //取后面六位,记得对应的二进制是以补码形式存在的
                temp[index++] = CH[num & 63];
                //63的二进制为:111111
                num >>= 6;
                // 为什么要右移6位?因为数组里面一共有64个有效字符。为什么要除5取余?因为一个int型要用4个字节表示,也就是32位。
            }
            for (int i = 0; i < length / 5; i++) {
                num = RANDOM.nextInt();
                for (int j = 0; j < 5; j++) {
                    temp[index++] = CH[num & 63];
                    num >>= 6;
                }
            }
            return new String(temp, 0, length);
        } else if (length == 0) {
            return "";
        } else {
            throw new IllegalArgumentException();
        }
    }
 
    public static void main(String[] args) {
        System.out.println(createRandomString(16));
    }
 
}