1. 程式人生 > >java 利用ID生成六位唯一驗證碼

java 利用ID生成六位唯一驗證碼

package com.hqjl.componentconfig.util;

import java.util.Random;

/**
 * @author chunying
 */
public class ShareCodeUtil {
/**
 * 邀請碼生成器,演算法原理:
 * 1) 獲取id: 1111111
 * 2) 使用自定義進位制轉為:gpm6
 * 3) 轉為字串,並在後面加'O'字元:gpm6o
 * 4)在後面隨機產生若干個隨機數字字元:gpm6o7
 * 轉為自定義進位制後就不會出現o這個字元,然後在後面加個'o',這樣就能確定唯一性。最後在後面產生一些隨機字元進行補全。
 */

    /** 自定義進位制(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;

    /** 序列最小長度 */
    private static final int s=6;

    /**
     * 根據ID生成六位隨機碼
     * @param id ID
     * @return 隨機碼
     */
    public static String toSerialCode(long 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() < s) {
            StringBuilder sb=new StringBuilder();
            sb.append(b);
            Random rnd=new Random();
            for(int i=1; i < s - 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) {
        String s = toSerialCode(20159284);
        System.out.println(s);
    }
}

 

 

這個是我從其他地方看見的  只為記錄一下