邀請碼生成器Java代碼
邀請碼生成器,可根據邀請碼反向算出用戶id
import java.util.Random;/**
- 邀請碼生成器,算法原理:<br/>
- 1) 獲取id: 1127738 <br/>
- 2) 使用自定義進制轉為:gpm6 <br/>
- 3) 轉為字符串,并在后面加'o'字符:gpm6o <br/>
- 4)在后面隨機產生若干個隨機數字字符:gpm6o7 <br/>
- 轉為自定義進制后就不會出現o這個字符,然后在后面加個'o',這樣就能確定唯一性。最后在后面產生一些隨機字符進行補全。<br/>
@author jiayu.qiu */ public class ShareCodeUtil {
/* 自定義進制(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); // System.out.println(num + "-->" + ind); buf[--charPos]=r[ind]; id /= binLen;} buf[--charPos]=r[(int)(id % binLen)]; // System.out.println(num + "-->" + num % 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; } // System.out.println(ind + "-->" + res);} return res; } }</pre>
來自:http://my.oschina.net/u/1469495/blog/470599