JAVA id 转 code (适用于邀请码)


网上没有找到想要的,就在网上一份邀请码生成器上做了改动

以下邀请码生成绝不重复并可与id相互转换

/**
 * @Author zyz
 * @Date$ 2020/7/1 10:33
 * 根据用户id生成不重复邀请码
 **/
public class ShareCodeUtil {
    /** 邀请码最小长度,生成邀请码小于该字段,自动补长  **/
    private static final int MIN_CODE_LENGTH = 6;
    /** 位数不足时自动补长时,充当分隔,该字段为保持唯一性,不放入下方的列表  **/
    private static final String STOP_CHAR = "Z";
    /** 考虑用户体验,此处去掉了 i o 1 0,具体列表内容自由换序  **/
    private static final String[] CHARS = new String[]{"2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H", "J", "K", "L", "M", "N", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y"};
    private static final int OFFSET = CHARS.length - 1;

    /**
     * 根据 id 生成邀请码
     * 如果是 6 位的邀请码只能支持 754137930 7亿5千万用户, 超出的id 会成为7位及以上的邀请码
     * @param id 用户id
     * @return 邀请码字符串
     */
    public static String id2ShareCode(int id) {
        String code = int2chars(id);
        int tailLength = MIN_CODE_LENGTH - code.length();
        if (tailLength > 1) {
            code = code + STOP_CHAR + codeTail(tailLength - 1);
        } else if (tailLength == 1) {
            code = code + STOP_CHAR;
        }
        return code;
    }

    /**
     * 根据邀请码 获取 id
     * @param code 邀请码
     * @return 用户id
     */
    public static int shareCode2id(String code) {
        int inx = code.indexOf(STOP_CHAR);
        if (inx > 0) {
            code = code.substring(0, inx);
        }
        return chars2int(code);
    }

    /**
     * 获取补长的邀请码(随机)
     * @param len 需要的长度
     * */
    private static String codeTail(int len) {
        String res = "";
        Random r = new Random();
        for (int i = 0; i < len; i++) {
            res += CHARS[r.nextInt(OFFSET)];
        }
        return res;
    }

    private static String int2chars(int id) {
        int x = id / OFFSET;
        int remainder = id % OFFSET;
        if (x == 0) {
            return CHARS[id];
        } else if (x < OFFSET) {
            return CHARS[x] + CHARS[remainder];
        } else {
            return int2chars(x) + CHARS[remainder];
        }
    }
    /**
* code 转 int
* */
private static int chars2int(String chars) {
int res = 0;
int codeLen = chars.length();
List<String> totalCharsList = Arrays.asList(CHARS);

for (int i = 0; i < codeLen; i++) {
String a = chars.substring(i, i+1);
if (STOP_CHAR.equals(a)) {
break;
}
if (totalCharsList.contains(a)) {
res = res * OFFSET + totalCharsList.indexOf(a);
} else {
res += 0;
break;
}
}
return res;
}
 }

参考:https://mengkang.net/595.html


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM