如何快速转换(重新编码)int64到字符限制字符串?

时间:2016-01-30 13:11:42

标签: c# string character-encoding recode

我正在寻找一种方法,将一个只包含数字[0,1,2,... 8,9]的字符串重新编码为另一个字符串,如数字和字母[0,1,... ..9,a,b,... z](作为例子)。结果字符串通常应短于仅数字字符串。该方法应该是可逆的,应该很快。 C#答案中的源代码将受到赞赏,但也欢迎gerneal的想法;-) 示例:

Input:  "1234567890123"
Output: "ar4cju7d"

应用于“ar4cju7d”的反转方法的输出应为“1234567890123。

1 个答案:

答案 0 :(得分:2)

如果您的输入始终是Int64,那么您可以检查Base36编码。这是一个sample implementation

// Edit: Slightly updated on 2011-03-29

/// <summary>
/// A Base36 De- and Encoder
/// </summary>
public static class Base36
{
    private const string CharList = "0123456789abcdefghijklmnopqrstuvwxyz";

    /// <summary>
    /// Encode the given number into a Base36 string
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    public static String Encode(long input)
    {
        if (input < 0) throw new ArgumentOutOfRangeException("input", input, "input cannot be negative");

        char[] clistarr = CharList.ToCharArray();
        var result = new Stack<char>();

        while (input != 0)
        {
            result.Push(clistarr[input % 36]);
            input /= 36;
        }

        return new string(result.ToArray());
    }

    /// <summary>
    /// Decode the Base36 Encoded string into a number
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    public static Int64 Decode(string input)
    {
        var reversed = input.ToLower().Reverse();
        long result = 0;
        int pos = 0;

        foreach (char c in reversed)
        {
            result += CharList.IndexOf(c) * (long)Math.Pow(36, pos);
            pos++;
        }

        return result;
    }
}

可以应用于您的示例:

long input = 1234567890123;
string encoded = Base36.Encode(input); // yields "fr5hugnf"
long originalInput = Base36.Decode(encoded); // yields 1234567890123