Quickest way to convert a base 10 number to any base in .NET?

后端 未结 12 1240
予麋鹿
予麋鹿 2020-11-22 04:07

I have and old(ish) C# method I wrote that takes a number and converts it to any base:

string ConvertToBase(int number, char[] baseChars);

12条回答
  •  时光说笑
    2020-11-22 04:30

    I was using this to store a Guid as a shorter string (but was limited to use 106 characters). If anyone is interested here is my code for decoding the string back to numeric value (in this case I used 2 ulongs for the Guid value, rather than coding an Int128 (since I'm in 3.5 not 4.0). For clarity CODE is a string const with 106 unique chars. ConvertLongsToBytes is pretty unexciting.

    private static Guid B106ToGuid(string pStr)
        {
            try
            {
                ulong tMutl = 1, tL1 = 0, tL2 = 0, targetBase = (ulong)CODE.Length;
                for (int i = 0; i < pStr.Length / 2; i++)
                {
                    tL1 += (ulong)CODE.IndexOf(pStr[i]) * tMutl;
                    tL2 += (ulong)CODE.IndexOf(pStr[pStr.Length / 2 + i]) * tMutl;
                    tMutl *= targetBase;
                }
                return new Guid(ConvertLongsToBytes(tL1, tL2));
            }
            catch (Exception ex)
            {
                throw new Exception("B106ToGuid failed to convert string to Guid", ex);
            }
        }
    

提交回复
热议问题