什么是转换为任意基C#函数的有效反演?

我需要将整数转换为base64字符表示。 我在这个post上使用OxA3的答案: 最快的方法是将基数为10的数字转换为.NET中的任何基数?

在给定字符串的情况下,如何将此反转以获取原始整数?

Joel Mueller的回答应该引导你了解base-64案例。

为了回应你在自己的答案中提供的初步代码,你肯定可以通过更改代码来完成你的for循环正在做的事情(实际上是O(N) IndexOf )来使用哈希查找(这应该是把它变成O(1))。

我的基础是假设baseChars是一个在类的构造函数中初始化的字段。 如果这是正确的,请进行以下调整:

 private Dictionary baseChars; // I don't know what your class is called. public MultipleBaseNumberFormatter(IEnumerable baseCharacters) { // check for baseCharacters != null and Count > 0 baseChars = baseCharacters .Select((c, i) => new { Value = c, Index = i }) .ToDictionary(x => x.Value, x => x.Index); } 

然后在你的StringToInt方法中:

 char next = encodedString[currentChar]; // No enumerating -- we've gone from O(N) to O(1)! if (!characterIndices.TryGetValue(next, out nextCharIndex)) { throw new ArgumentException("Input includes illegal characters."); } 

我在这里有一个工作版本的第一遍,虽然我不确定它的效率如何。

 public static int StringToInt(string encodedString, char[] baseChars) { int result = 0; int sourceBase = baseChars.Length; int nextCharIndex = 0; for (int currentChar = encodedString.Length - 1; currentChar >= 0; currentChar--) { char next = encodedString[currentChar]; // For loop gets us: baseChar.IndexOf(char) => int for (nextCharIndex = 0; nextCharIndex < baseChars.Length; nextCharIndex++) { if (baseChars[nextCharIndex] == next) { break; } } // For character N (from the end of the string), we multiply our value // by 64^N. eg. if we have "CE" in hex, F = 16 * 13. result += (int)Math.Pow(baseChars.Length, encodedString.Length - 1 - currentChar) * nextCharIndex; } return result; } 

这是一个使用Linqfunction和.NET Framework 4.0 Zip扩展的版本来执行计算。

 public static int StringToInt(string encodedString, char[] baseChars) { int sourceBase = baseChars.Length; var dict = baseChars .Select((c, i) => new { Value = c, Index = i }) .ToDictionary(x => x.Value, x => x.Index); return encodedString.ToCharArray() // Get a list of positional weights in descending order, calcuate value of weighted position .Zip(Enumerable.Range(0,encodedString.Length).Reverse(), (f,s) => dict[f] * (int)Math.Pow(sourceBase,s)) .Sum(); } 

仅供参考,在函数外部计算字典对于大批量的转换将更有效。

如果base-64真的是您需要的而不是“任何基础”,那么您需要的所有内容都已内置到框架中:

 int orig = 1337; byte[] origBytes = BitConverter.GetBytes(orig); string encoded = Convert.ToBase64String(origBytes); byte[] decoded = Convert.FromBase64String(encoded); int converted = BitConverter.ToInt32(decoded, 0); System.Diagnostics.Debug.Assert(orig == converted); 

这是一个完整的解决方案,可将base10编号转换为baseK并返回:

 public class Program { public static void Main() { int i = 100; Console.WriteLine("Int: " + i); // Default base definition. By moving chars around in this string, we can further prevent // users from guessing identifiers. var baseDefinition = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; //var baseDefinition = "WBUR17GHO8FLZIA059M4TESD2VCNQKXPJ63Y"; // scrambled to minimize guessability // Convert base10 to baseK var newId = ConvertToBaseK(i, baseDefinition); Console.WriteLine(string.Format("To base{0} (short): {1}", baseDefinition.Length, newId)); // Convert baseK to base10 var convertedInt2 = ConvertToBase10(newId, baseDefinition); Console.WriteLine(string.Format("Converted back: {0}", convertedInt2)); } public static string ConvertToBaseK(int val, string baseDef) { string result = string.Empty; int targetBase = baseDef.Length; do { result = baseDef[val % targetBase] + result; val = val / targetBase; } while (val > 0); return result; } public static int ConvertToBase10(string str, string baseDef) { double result = 0; for (int idx = 0; idx < str.Length; idx++) { var idxOfChar = baseDef.IndexOf(str[idx]); result += idxOfChar * System.Math.Pow(baseDef.Length, (str.Length-1) - idx); } return (int)result; } }