C#十进制与任意进制的转换
1 /// <summary> 2 /// 将十进制转换为指定的进制 3 /// </summary> 4 /// <param name="Val">十进制值</param> 5 /// <param name="TargetRadix">目标进制</param> 6 /// <param name="BaseChar">基数列表(长度必须大于源字符串进制,无I,O)</param> 7 /// <returns></returns> 8 public static string JinZhiConvert(ulong Val, int TargetRadix = 0, string BaseChar = "0123456789ABCDEFGHJKLMNPQRSTUVWXYZ") 9 { 10 if (TargetRadix == 0 && BaseChar.Length == 0) return "长度与基数不能同时为零"; 11 if (TargetRadix <= 0) TargetRadix = BaseChar.Length; 12 List<string> r = new List<string>(); 13 do 14 { 15 ulong y = Val % (ulong)TargetRadix; 16 r.Add(BaseChar[Convert.ToInt32(y)].ToString()); 17 Val = Convert.ToUInt64(Math.Floor(Val / (decimal)TargetRadix)); 18 } while (Val > 0); 19 r.Reverse(); 20 return string.Join("", r.ToArray()); 21 } 22 23 24 /// <summary> 25 /// 将任意进制转化为十制 26 /// </summary> 27 /// <param name="Val">任意进制的字任串</param> 28 /// <param name="SourceRadix">源字符串的进制</param> 29 /// <param name="BaseChar">基数列表(长度必须大于源字符串进制,无I,O)</param> 30 /// <returns></returns> 31 public static ulong JinZhiConvert(string Val, int SourceRadix = 0, string BaseChar = "0123456789ABCDEFGHJKLMNPQRSTUVWXYZ") 32 { 33 ulong r = 0; 34 if (BaseChar == "") return 0; 35 if (SourceRadix == 0) SourceRadix = BaseChar.Length; 36 List<char> v = Val.ToCharArray().ToList(); 37 v.Reverse(); 38 for (int i = 0; i < v.Count; i++) 39 { 40 int index = BaseChar.IndexOf(v[i]); 41 if (index > -1) 42 r += Convert.ToUInt64(index * Math.Pow(SourceRadix, i)); 43 } 44 return r; 45 }