根据自增ID生成不重复序列号
网上看到一个例子,源地址:https://www.aliyun.com/jiaocheng/536419.html 借鉴修改一下
实现根据long类型的用户ID生成6位随机邀请码,并且根据邀请码能算出用户ID。代码如下:
/// <summary>
/// 不重复随机字符串类
/// </summary>
public class SerialNumberHelper
{
/** 自定义进制(选择你想要的进制数,不能重复且最好不要0、1这些容易混淆的字符) */
private static readonly 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 readonly char b = 'a';
/** 进制长度 */
private static readonly int binLen = r.Length;
/** 邀请码长度 */
private static readonly int s = 6;
/// <summary>
/// 根据ID生成随机码
/// </summary>
/// <param name="id">ID</param>
/// <returns></returns>
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.Next(binLen)]);
}
str += sb.ToString();
}
return str;
}
/// <summary>
/// 根据随机码生成ID
/// </summary>
/// <param name="code"></param>
/// <returns></returns>
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;
}
}
上面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() < s) {
StringBuilder sb=new StringBuilder();
sb.append(e.subSequence(0, s-str.length()));
str+=sb.toString();
}
return str;
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix