C#實現整型數據字任意編碼任意進制的轉換和逆轉換
阿新 • • 發佈:2018-06-23
har eve blog ons rst each adapter AC CA
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 6 namespace ConsoleApplication1 7 { 8 9 public class Number 10 { 11 public string Characters 12 { 13 get; 14 set; 15 } 1617 public int Length 18 { 19 get 20 { 21 if (Characters != null) 22 return Characters.Length; 23 else 24 return 0; 25 } 26 27 } 28 29 public Number()30 { 31 Characters = "0123456789"; 32 } 33 34 public Number(string characters) 35 { 36 Characters = characters; 37 } 38 39 /// <summary> 40 /// 數字轉換為指定的進制形式字符串 41 /// </summary> 42 /// <param name="number"></param>43 /// <returns></returns> 44 public string ToString(long number) 45 { 46 List<string> result = new List<string>(); 47 long t = number; 48 49 while (t > 0) 50 { 51 var mod = t % Length; 52 t = Math.Abs(t / Length); 53 var character = Characters[Convert.ToInt32(mod)].ToString(); 54 result.Insert(0, character); 55 } 56 57 return string.Join("", result.ToArray()); 58 } 59 60 /// <summary> 61 /// 指定字符串轉換為指定進制的數字形式 62 /// </summary> 63 /// <param name="str"></param> 64 /// <returns></returns> 65 public long FromString(string str) 66 { 67 long result = 0; 68 int j = 0; 69 foreach (var ch in new string(str.ToCharArray().Reverse().ToArray())) 70 { 71 if (Characters.Contains(ch)) 72 { 73 result += Characters.IndexOf(ch) * ((long)Math.Pow(Length, j)); 74 j++; 75 } 76 } 77 return result; 78 } 79 80 } 81 82 83 84 class Program 85 { 86 static void Print(long number, Number adapter) 87 { 88 Console.WriteLine("輸入數字:{0}", number); 89 Console.WriteLine("規則:{0}\t\t進制:{1}進制", adapter.Characters,adapter.Length); 90 var numtostr = adapter.ToString(number); 91 Console.WriteLine("轉換結果:{0}", numtostr); 92 var strtonum = adapter.FromString(numtostr); 93 Console.WriteLine("逆向轉換結果:{0}", strtonum); 94 Console.WriteLine(); 95 Console.WriteLine("============ 無聊的分割線 ============"); 96 Console.WriteLine(); 97 } 98 99 static void Main(string[] args) 100 { 101 //傳統的2進制 102 Number n1 = new Number("01"); 103 //傳統的8進制 104 Number n2 = new Number("01234567"); 105 //傳統的16進制 106 Number n3 = new Number("0123456789ABCDEF"); 107 //自定義編碼的N進制,這個可以用來做驗證碼? 108 Number n4 = new Number("爹媽說名字太長躲在樹後面會被部落發現"); 109 //山寨一個短網址 110 Number n5 = new Number("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"); 111 112 Print(65535, n1); 113 Print(65535, n2); 114 Print(65535, n3); 115 Print(65535, n4); 116 Print(165535, n5); 117 118 Console.ReadKey(); 119 120 } 121 } 122 }
轉自:https://www.cnblogs.com/linxuanchen/archive/2012/02/02/2336099.html
C#實現整型數據字任意編碼任意進制的轉換和逆轉換