38 lines
1.0 KiB
C#
38 lines
1.0 KiB
C#
using System.Text;
|
|
|
|
namespace Atomx.Utils.Extension
|
|
{
|
|
public static class IdCodeExtension
|
|
{
|
|
private static readonly char[] Base62Chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".ToCharArray();
|
|
|
|
/// <summary>
|
|
/// 将long类型ID编码为10位Base62邀请码
|
|
/// </summary>
|
|
public static string IdToCode(this long id)
|
|
{
|
|
ulong value = (ulong)id;
|
|
var sb = new StringBuilder();
|
|
for (int i = 0; i < 10; i++)
|
|
{
|
|
sb.Insert(0, Base62Chars[(int)(value % 62)]);
|
|
value /= 62;
|
|
}
|
|
return sb.ToString();
|
|
}
|
|
|
|
/// <summary>
|
|
/// 将10位Base62邀请码还原为long类型ID
|
|
/// </summary>
|
|
public static long CodeToId(this string code)
|
|
{
|
|
ulong value = 0;
|
|
foreach (var c in code)
|
|
{
|
|
value = value * 62 + (ulong)Array.IndexOf(Base62Chars, c);
|
|
}
|
|
return (long)value;
|
|
}
|
|
}
|
|
}
|