Hex62Convertor.cs 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. namespace JiaZhiQuan.Common.Utils
  2. {
  3. public class Hex62Convertor
  4. {
  5. private static string keys = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";//编码,可加一些字符也可以实现72,96等任意进制转换,但是有符号数据不直观,会影响阅读。
  6. private static int exponent = keys.Length;//幂数
  7. /// <summary>
  8. /// long value type to 62 string
  9. /// </summary>
  10. public static string Long2Str(long value)
  11. {
  12. string result = string.Empty;
  13. do
  14. {
  15. long index = value % exponent;
  16. result = keys[(int)index] + result;
  17. value = (value - index) / exponent;
  18. }
  19. while (value > 0);
  20. return result;
  21. }
  22. /// <summary>
  23. /// 62 encode string to long
  24. /// </summary>
  25. public static long Str2Long(string value)
  26. {
  27. long result = 0;
  28. for (int i = 0; i < value.Length; i++)
  29. {
  30. int x = value.Length - i - 1;
  31. result += keys.IndexOf(value[i]) * Pow(exponent, x);// Math.Pow(exponent, x);
  32. }
  33. return result;
  34. }
  35. /// <summary>
  36. /// 一个数据的N次方
  37. /// </summary>
  38. private static long Pow(long baseNo, long x)
  39. {
  40. long value = 1;////1 will be the result for any number's power 0.任何数的0次方,结果都等于1
  41. while (x > 0)
  42. {
  43. value = value * baseNo;
  44. x--;
  45. }
  46. return value;
  47. }
  48. }
  49. }