根据id生成id随机码
使用场景:需要把id信息暴露出来,但是id又过长,而且不安全,MD5摘要又太长,需要根据id生成短的标识,就用了随机码。
1、随机码位数CODE_LEN为最小长度,如果id很长,随机码的位数也会增加
2、如果id小于CODE_LEN位,则不同id可能会生成一样的随机码,在短的id后面补0,保证原始id长度大于CODE_LEN长度
3、支持id转随机码,随机码转id的操作
4、用于生成固定随机码id最小长度要大于CODE_LEN,不足补0
5、代码来源网络,经修改测试后的修复代码
public class TestSerialCode {
/** 自定义进制(0,1没有加入,容易与o,l混淆) */
private static final char[] r = new char[]{'Q', 'W', 'E', '8', 'A', 'S', '2', 'D', 'Z', 'X', '9', 'C', '7', 'P', '5', 'I', 'K', '3', 'M', 'J', 'U', 'F', 'R', '4', 'V', 'Y', 'l', 'T', 'N', '6', 'B', 'G', 'H'};
/** (不能与自定义进制有重复) */
private static final char b = 'O';
/** 进制长度 */
private static final int binLen = r.length;
/** 序列最小长度 */
public static final int CODE_LEN = 6;
/** 用于生成固定随机码id最小长度 */
public static final int ID_LEN = 7;
/**
* 根据ID生成六位随机码
* @param id ID
* @return 随机码
*/
public static String toSerialCode(long id) {
System.out.println("原始id:" + id);
// 判断id多少位
String replace = String.format("%-" + ID_LEN + "s", id).replace(' ', '0');
id = Long.valueOf(replace);
System.out.println("补位后id:" + id);
char[] buf = new char[32];
int charPos = 32;
while ((id / binLen) > 0) {
int ind = (int) (id % binLen);
buf[--charPos] = r[ind];
id /= binLen;
}
buf[--charPos] = r[(int) (id % binLen)];
String str = new String(buf, charPos, (32 - charPos));
// 不够长度的自动随机补全
if (str.length() < CODE_LEN) {
StringBuilder sb = new StringBuilder();
sb.append(b);
Random rnd = new Random();
for (int i = 1; i < CODE_LEN - str.length(); i++) {
sb.append(r[rnd.nextInt(binLen)]);
}
str += sb.toString();
}
return str;
}
public static long codeToId(String code) {
char chs[] = code.toCharArray();
long res = 0L;
for (int i = 0; i < chs.length; i++) {
int ind = 0;
for (int j = 0; j < binLen; j++) {
if (chs[i] == r[j]) {
ind = j;
break;
}
}
if (chs[i] == b) {
break;
}
if (i > 0) {
res = res * binLen + ind;
} else {
res = ind;
}
}
return res;
}
public static void main(String[] args) {
System.out.println(String.format("%-" + ID_LEN + "s", Long.parseLong("1235898")).replace(' ', '0'));
/* 5762
57621960
57622960*/
Long s1 = 21881607L;
System.out.println("原始id:" + s1);
String s11 = toSerialCode(s1);
System.out.println("转出随机码:" + s11);
long s12 = codeToId(s11);
System.out.println("随机码转出id:" + s12);
Long s2 = 21881609L;
System.out.println("原始id:" + s2);
String s22 = toSerialCode(s2);
System.out.println("转出随机码:" + s22);
long s23 = codeToId(s22);
System.out.println("随机码转出id:" + s23);
Long s3 = 218512L;
System.out.println("原始id:" + s3);
String s33 = toSerialCode(s3);
System.out.println("转出随机码:" + s33);
long s34 = codeToId(s33);
System.out.println("随机码转出id:" + s34);
}
public static String addZeroForNum(String str, int strLength) {
int strLen = str.length();
if (strLen < strLength) {
while (strLen < strLength) {
StringBuffer sb = new StringBuffer();
sb.append("0").append(str);// 左补0
// sb.append(str).append("0");//右补0
str = sb.toString();
strLen = str.length();
}
}
return str;
}
}