10进制与62进制互相转换

遇到将数字(Decimal)以62进制编码的问题,这里所谓62进制是指采用0~9A~Za~z等62个字符进行编码(按ASCII顺序由小到大)。

Note:这里以`6位编码`为例实现(C#,其他语言类似,或许有更有效的方式),实际中可根据需要调整,不过注意其表述的数值大小范围(eg:6位编码最大值:56800235583(long))。

10进制——>62进制

/// <summary>
/// 将数字转为62进制
/// </summary>
/// <param>待转换的数字</param>
/// <returns>编码字符串</returns>
public static string EncodeStr(long num)
{
    int scale = 62;
    StringBuilder sb = new StringBuilder();
    char[] charArray = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".ToCharArray();

long remainder = 0;

do
    {
        remainder = num % scale;
        sb.Append(charArray[remainder]);
        num = num / scale;
    }
    while (num > scale - 1);

sb.Append(charArray[num]);

char[] chars = sb.ToString().ToCharArray();
    Array.Reverse(chars);
    string result = new string(chars);

// 6 bits are required, add leading zeros when the encoded string < 6 long
    return result.PadLeft(6, '0');
}

62进制——>10进制

/// <summary>
/// 62进制字符串转为数字
/// </summary>
/// <param>编码字符串</param>
/// <returns>解码后的数字</returns>
public static long DecodeNum(string str)
{
    int scale = 62;
    string charArray = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";

// Trim the leading zeros first           
    str = Regex.Replace(str, "^0*", "");

long num = 0;
    int index = 0;
    for(int i = 0; i < str.Length; i++)
    {
        index = charArray.IndexOf(str[i]);
        num += (long)(index * (Math.Pow(scale, str.Length - i - 1)));
    }

return num;
}

Linux公社的RSS地址https://www.linuxidc.com/rssFeed.aspx

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/344fa8c60e1486a0b8e88db174657260.html