根据用户ID生成不重复的最小6位随机邀请码 您所在的位置:网站首页 邀请码6位 根据用户ID生成不重复的最小6位随机邀请码

根据用户ID生成不重复的最小6位随机邀请码

2024-01-22 02:08| 来源: 网络整理| 查看: 265

网上看到一个例子,借鉴修改一下

实现根据long类型的用户ID生成6位随机邀请码,并且根据邀请码能算出用户ID。代码如下:

/** 自定义进制(选择你想要的进制数,不能重复且最好不要0、1这些容易混淆的字符) */ private static final char[] r=new char[]{'q', 'w', 'e', '8', 's', '2', 'd', 'z', 'x', '9', 'c', '7', 'p', '5', 'k', '3', 'm', 'j', 'u', 'f', 'r', '4', 'v', 'y', 't', 'n', '6', 'b', 'g', 'h'}; /** 定义一个字符用来补全邀请码长度(该字符前面是计算出来的邀请码,后面是用来补全用的) */ private static final char b='a'; /** 进制长度 */ 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() 0) { res=res * binLen + ind; } else { res=ind; } } return res; }

 上面6位邀请码能表示的最大ID为728999999(“hhhhhh”),729000000(“wqqqqqq”)就要进位了。

上面方法同一个id生成的邀请码不唯一,如果想唯一则定义一个补位字符串就可以了:

/** 补位字符串 */ private static final String e="atgsghj"; /** * 根据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()


【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有