fork(1) download
  1. import java.util.List;
  2. import java.math.BigInteger;
  3. import java.util.ArrayList;
  4. import java.util.Collections;
  5.  
  6. /**
  7.  * @author Victor
  8.  */
  9. public class Main {
  10.  
  11. public static void main(String[] args) {
  12. // Passa o alfabeto como parâmetro. Tem 62 caracteres aqui, então são 62 símbolos.
  13. BaseN bn = new BaseN("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz");
  14. String x = "The quick brown fox jumps over a lazy dog";
  15. System.out.println(x);
  16. String a = bn.encode(x);
  17. System.out.println(a); // Escreve "1u9WLfG65OMtVkQWPtWDcC6o8IjI5td5l9DzpilIK4Nyx81tKLRrStPj"
  18. String b = bn.decode(a);
  19. System.out.println(b); // Escreve "The quick brown fox jumps over a lazy dog"
  20. }
  21. }
  22.  
  23. class BaseN {
  24. private static final BigInteger BI_256 = BigInteger.valueOf(256);
  25.  
  26. private final String base;
  27. private final BigInteger radix;
  28.  
  29. public BaseN(String base) {
  30. this.base = base;
  31. this.radix = BigInteger.valueOf(base.length());
  32. }
  33.  
  34. public String encode(String text) {
  35. byte[] bytes = text.getBytes();
  36. for (byte b : bytes) {
  37. big = big.multiply(BI_256).add(BigInteger.valueOf(b));
  38. }
  39. StringBuilder sb = new StringBuilder(bytes.length * 4 / 3 + 2);
  40. while (!BigInteger.ZERO.equals(big)) {
  41. BigInteger[] parts = big.divideAndRemainder(radix);
  42. int small = parts[1].intValue();
  43. big = parts[0];
  44. sb.append(base.charAt(small));
  45. }
  46.  
  47. return sb.reverse().toString();
  48. }
  49.  
  50. public String decode(String text) {
  51. BigInteger big = BigInteger.ZERO;
  52. for (char c : text.toCharArray()) {
  53. int i = base.indexOf(c);
  54. if (i == -1) throw new IllegalArgumentException();
  55. big = big.multiply(radix).add(BigInteger.valueOf(i));
  56. }
  57.  
  58. List<Byte> byteList = new ArrayList<>(text.length());
  59. while (!BigInteger.ZERO.equals(big)) {
  60. BigInteger[] parts = big.divideAndRemainder(BI_256);
  61. int small = parts[1].intValue();
  62. big = parts[0];
  63. byteList.add((byte) small);
  64. }
  65. Collections.reverse(byteList);
  66.  
  67. byte[] r = new byte[byteList.size() - 1];
  68. int i = 0;
  69. for (Byte b : byteList) {
  70. if (i > 0) r[i - 1] = b;
  71. i++;
  72. }
  73. return new String(r);
  74. }
  75. }
Success #stdin #stdout 0.07s 380160KB
stdin
Standard input is empty
stdout
The quick brown fox jumps over a lazy dog
1u9WLfG65OMtVkQWPtWDcC6o8IjI5td5l9DzpilIK4Nyx81tKLRrStPj
The quick brown fox jumps over a lazy dog