说明:【数字 → 字符串】、【字符串 → 数字】互为逆运算,数字不同,转换的字符串也不同,可用于短连接的id转换
import java.util.HashMap;
/**
*
* 将数字转换为字母组合,再转换为数字,可以得到相同的结果
*/
public class PECode {
/**
* 打乱改字符数组的组合顺序,可以得到不同的转换结果
*/
public static final char[] array = {'q', 'w', 'e', 'r', 't', 'y', 'u', 'i', 'o', 'p', 'a', 's', 'd', 'f', 'g',
'h', 'j', 'k', 'l', 'z', 'x', 'c', 'v', 'b', 'n', 'm', '8', '5', '2', '7', '3', '6', '4', '0', '9', '1',
'Q', 'W', 'E', 'R', 'T', 'Y', 'U', 'I', 'O', 'P', 'A', 'S', 'D', 'F', 'G', 'H', 'J', 'K', 'L', 'Z', 'X',
'C', 'V', 'B', 'N', 'M'};
private static final HashMap<Character, Integer> indexMap = createIndexMap();
public static String encode(Long number) {
if (number <= 0) throw new IllegalArgumentException("Number must be positive.");
StringBuilder result = new StringBuilder(0);
while (number > 0) {
int index = (int) (number % array.length);
result.insert(0, array[index]);
number /= array.length;
}
return result.toString();
}
public static Long decode(String input) {
if (input == null || input.isEmpty())
throw new IllegalArgumentException("Input string cannot be null or empty.");
long result = 0L;
long multiple = 1;
for (int i = input.length() - 1; i >= 0; i--) {
char c = input.charAt(i);
int index = indexMap.get(c);
result += index * multiple;
multiple *= array.length;
}
return result;
}
private static HashMap<Character, Integer> createIndexMap() {
HashMap<Character, Integer> map = new HashMap<>();
for (int i = 0; i < array.length; i++) {
map.put(array[i], i);
}
return map;
}
}
评论区