php不太会用,乱写的但是实现了。 function createCode($userId) { static $sourceString = [ 2,3,4,5,6,7,8,9,10, 'b','c','d','e','f', 'g','h','i','j','k','l', 'm','n','p','q','r', 's','t','u','v','w','x', 'y','z' ]; $suffix_char = 'a'; $bin_len = count($sourceString); $code_len = 6; $num = $userId; $char_len = array(); $charpos = $code_len; while((int)($num/$bin_len)>0) { echo "while"; $mod = $num % $bin_len; $char_len[--$charpos]=$sourceString[$mod]; echo $char_len; //每循环一次,去掉一个循环长度, $num = $num/$bin_len; } $char_len[ --$charpos]=$sourceString[$num % $bin_len]; $result = ''; for ($i=0;$i<6;$i++){ if (trim($char_len[$i])!=''){ $result = $result.$char_len[$i]; } } $len = strlen($result); if ($len <$code_len){ $result = str_pad($result,6,$suffix_char,STR_PAD_LEFT); } return $result; }
===========================================以下是java
网上转载的===
public class ShareCodeUtils {
/**
* 自定义进制(0,1没有加入,容易与o,l混淆),数组顺序可进行调整增加反推难度,A用来补位因此此数组不包含A,共31个字符。
*/
private static final char[] BASE = new char[]{'H', 'V', 'E', '8', 'S', '2', 'D', 'Z', 'X', '9', 'C', '7', 'P',
'5', 'I', 'K', '3', 'M', 'J', 'U', 'F', 'R', '4', 'W', 'Y', 'L', 'T', 'N', '6', 'B', 'G', 'Q'};
/**
* A补位字符,不能与自定义重复,这里实际是用做分割符,当位数不够append一个A补位,剩余再不满足就用随机补位
*/
private static final char SUFFIX_CHAR = 'A';
/**
* 进制长度
*/
private static final int BIN_LEN = BASE.length;
/**
* 生成邀请码最小长度
*/
private static final int CODE_LEN = 6;
/**
* ID转换为邀请码
*
* @param id
* @return
*/
public static String idToCode(Long id) {
char[] buf = new char[BIN_LEN];
int charPos = BIN_LEN;
// 当id除以数组长度结果大于0,则进行取模操作,并以取模的值作为数组的坐标获得对应的字符
while (id / BIN_LEN > 0) {
int index = (int) (id % BIN_LEN);
buf[--charPos] = BASE[index];
id /= BIN_LEN;
}
如果一个数组长度为31,那么取它最后一个值应该是buf[31-1]所以这里是buf[--charPos]
buf[--charPos] = BASE[(int) (id % BIN_LEN)];
// 将字符数组转化为字符串,new String(数组,起始位置,长度)
String result = new String(buf, charPos, BIN_LEN - charPos);
// 长度不足指定长度则随机补全
int len = result.length();
if (len < CODE_LEN) {
StringBuilder sb = new StringBuilder();
sb.append(SUFFIX_CHAR);
Random random = new Random();
// 去除SUFFIX_CHAR本身占位之后需要补齐的位数
for (int i = 0; i < CODE_LEN - len - 1; i++) {
sb.append(BASE[random.nextInt(BIN_LEN)]);
result += sb.toString();
}
return result;
}