12.3 C#任意进制的转换和逆转换

C#实现整型数据字任意编码任意进制的转换和逆转换

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. namespace ConsoleApplication1
  6. {
  7. public class Number
  8. {
  9. public string Characters
  10. {
  11. get;
  12. set;
  13. }
  14. public int Length
  15. {
  16. get
  17. {
  18. if (Characters != null)
  19. return Characters.Length;
  20. else
  21. return 0;
  22. }
  23. }
  24. public Number()
  25. {
  26. Characters = "0123456789";
  27. }
  28. public Number(string characters)
  29. {
  30. Characters = characters;
  31. }
  32. /// <summary>
  33. /// 数字转换为指定的进制形式字符串
  34. /// </summary>
  35. /// <param name="number"></param>
  36. /// <returns></returns>
  37. public string ToString(long number)
  38. {
  39. List<string> result = new List<string>();
  40. long t = number;
  41. while (t > 0)
  42. {
  43. var mod = t % Length;
  44. t = Math.Abs(t / Length);
  45. var character = Characters[Convert.ToInt32(mod)].ToString();
  46. result.Insert(0, character);
  47. }
  48. return string.Join("", result.ToArray());
  49. }
  50. /// <summary>
  51. /// 指定字符串转换为指定进制的数字形式
  52. /// </summary>
  53. /// <param name="str"></param>
  54. /// <returns></returns>
  55. public long FromString(string str)
  56. {
  57. long result = 0;
  58. int j = 0;
  59. foreach (var ch in new string(str.ToCharArray().Reverse().ToArray()))
  60. {
  61. if (Characters.Contains(ch))
  62. {
  63. result += Characters.IndexOf(ch) * ((long)Math.Pow(Length, j));
  64. j++;
  65. }
  66. }
  67. return result;
  68. }
  69. }
  70. class Program
  71. {
  72. static void Print(long number, Number adapter)
  73. {
  74. Console.WriteLine("输入数字:{0}", number);
  75. Console.WriteLine("规则:{0}\t\t进制:{1}进制", adapter.Characters,adapter.Length);
  76. var numtostr = adapter.ToString(number);
  77. Console.WriteLine("转换结果:{0}", numtostr);
  78. var strtonum = adapter.FromString(numtostr);
  79. Console.WriteLine("逆向转换结果:{0}", strtonum);
  80. Console.WriteLine();
  81. Console.WriteLine("============ 无聊的分割线 ============");
  82. Console.WriteLine();
  83. }
  84. static void Main(string[] args)
  85. {
  86. //传统的2进制
  87. Number n1 = new Number("01");
  88. //传统的8进制
  89. Number n2 = new Number("01234567");
  90. //传统的16进制
  91. Number n3 = new Number("0123456789ABCDEF");
  92. //自定义编码的N进制,这个可以用来做验证码?
  93. Number n4 = new Number("爹妈说名字太长躲在树后面会被部落发现");
  94. //山寨一个短网址
  95. Number n5 = new Number("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ");
  96. Print(65535, n1);
  97. Print(65535, n2);
  98. Print(65535, n3);
  99. Print(65535, n4);
  100. Print(165535, n5);
  101. Console.ReadKey();
  102. }
  103. }
  104. }