Heartsuit's Simple Blog

A place to hold mainly reading notes, and some technical stuff occasionally. 这里主要是一些读书笔记、感悟;还有部分技术相关的内容。


Project maintained by heartsuit Hosted on GitHub Pages — Theme by mattgraham

10进制与62进制互相转换

目录[-]

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

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

10进制——>62进制

/// <summary>
/// 将数字转为62进制
/// </summary>
/// <param name="num">待转换的数字</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 name="str">编码字符串</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;
}

If you have any questions or any bugs are found, please feel free to contact me.

Your comments and suggestions are welcome!


「说点什么吧😊~~😊」: