C#根据UserId生成可逆的唯一邀请码

1.定义全局变量

//自定义进制(0、O没有加入,容易混淆;同时排除X,用X补位)
private static char[] r = new char[] { 'Q', 'W', 'E', '8', 'A', 'S', '2', 'D', 'Z', '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 char b = 'X';
//进制长度
private static int binLen = r.Length;
//生成的邀请码长度
private static int length = 6;

2.调用执行方法

public void ProcessRequest(HttpContext context)
{
    context.Response.ContentType = "text/plain";

    //用户id
    int userId = 1;
    //生成邀请码
    string code = Encode(userId);
    //根据邀请码返回用户id
    string decode = Decode(code);
    context.Response.Write(code + ',' + decode);
}

3.根据ID生成六位随机邀请码

/// <summary>
/// 根据ID生成六位随机邀请码
/// </summary>
/// <param name="id">用户id</param>
/// <returns>返回6位邀请码</returns>
public static string Encode(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 < length)
    {
        StringBuilder sb = new StringBuilder();
        sb.Append(b);
        Random rnd = new Random();
        for (int i = 1; i < length - str.Length; i++)
        {
            sb.Append(r[rnd.Next(binLen)]);
        }
        str += sb.ToString();
    }
    return str;
}

4.根据随机邀请码获得UserId

/// <summary>
/// 根据随机邀请码获得UserId
/// </summary>
/// <param name="code">邀请码</param>
/// <returns>返回用户id</returns>
public static string Decode(string code)
{
    char[] chs = code.ToArray();
    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.ToString();
}
后端开发

C#委托操作实例

2021-11-16 10:42:11

后端开发

ashx读写MySql数据库

2021-11-16 11:29:37

0 条回复 A文章作者 M管理员
    暂无讨论,说说你的看法吧
个人中心
购物车
优惠劵
今日签到
有新私信 私信列表
搜索