DecimalConverter.java 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. package com.usoft.bizcode.utils;
  2. import java.math.BigInteger;
  3. /**
  4. * 十进制(Decimal)转换为 2-62进制
  5. *
  6. * @author: wangcanyi
  7. * @date: 2018-08-23 10:32
  8. */
  9. public class DecimalConverter {
  10. private static final String[] NUM_TABLE = {"0", "1", "2", "3", "4", "5",
  11. "6", "7", "8", "9", "a", "b", "c", "d", "e", "f", "g", "h", "i",
  12. "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v",
  13. "w", "x", "y", "z", "A", "B", "C", "D", "E", "F", "G", "H", "I",
  14. "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V",
  15. "W", "X", "Y", "Z"};
  16. private static final int MAX_RADIX = 62;
  17. private static final int MIN_RADIX = 2;
  18. /**
  19. * 十进制(Decimal)转换为 2-62进制
  20. *
  21. * @param decimalText 10进制数
  22. * @param radix 几进制
  23. * @return
  24. */
  25. public static String fromDecimal(String decimalText, int radix) {
  26. if (decimalText == null || decimalText.trim().length() < 1) {
  27. return decimalText;
  28. }
  29. BigInteger radixInteger = new BigInteger(Integer.toString(radix));
  30. BigInteger decimalInteger = new BigInteger(decimalText);
  31. return fromDecimal(decimalInteger, radixInteger);
  32. }
  33. /**
  34. * 十进制(Decimal)转换为 2-62进制
  35. *
  36. * @param decimalValue 10进制数
  37. * @param radixInteger 几进制
  38. * @return
  39. */
  40. public static String fromDecimal(BigInteger decimalValue,
  41. BigInteger radixInteger) {
  42. if (radixInteger.intValue() < MIN_RADIX
  43. || radixInteger.intValue() > MAX_RADIX) {
  44. throw new IllegalArgumentException("只能转换为2-62进制");
  45. }
  46. if (decimalValue.compareTo(BigInteger.ZERO) < 0) {
  47. return "-" + fromDecimal(decimalValue.negate(), radixInteger);
  48. }
  49. if (decimalValue.compareTo(radixInteger) < 0) {
  50. return NUM_TABLE[decimalValue.intValue()];
  51. } else {
  52. BigInteger[] result = decimalValue.divideAndRemainder(radixInteger);
  53. // 整除的余数
  54. BigInteger suffix = result[1];
  55. String prefix = fromDecimal(result[0], radixInteger);
  56. return prefix + NUM_TABLE[suffix.intValue()];
  57. }
  58. }
  59. }