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