Skip to content

Instantly share code, notes, and snippets.

@renaudcerrato
Created February 2, 2017 14:00
Show Gist options
  • Save renaudcerrato/b535b0fa0398234ceda60d9e6b8fd446 to your computer and use it in GitHub Desktop.
Save renaudcerrato/b535b0fa0398234ceda60d9e6b8fd446 to your computer and use it in GitHub Desktop.
import java.math.BigInteger;
final public class Base63 {
static public final char[] CHARSET = new char[]{'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','_'};
static private final BigInteger BASE = BigInteger.valueOf(CHARSET.length);
public static String encode(BigInteger integer) {
final StringBuilder sb = new StringBuilder();
BigInteger[] r = new BigInteger[]{integer, null};
do {
r = r[0].divideAndRemainder(BASE);
sb.insert(0, CHARSET[r[1].intValue()]);
}while(r[0].compareTo(BigInteger.ZERO) != 0);
return sb.toString();
}
static public BigInteger decode(String value) {
final int size = value.length();
BigInteger result = BigInteger.ZERO;
BigInteger m = BigInteger.ONE;
for(int i = 0; i < size; i++) {
char c = value.charAt(size - 1 - i);
if(c == '_')
result = result.add(BigInteger.valueOf(62).multiply(m));
else if(c <= '9')
result = result.add(BigInteger.valueOf(c - '0').multiply(m));
else if(c <= 'Z')
result = result.add(BigInteger.valueOf(c - 'A' + 10).multiply(m));
else if(c <= 'z')
result = result.add(BigInteger.valueOf(c - 'a' + 36).multiply(m));
else
throw new IllegalArgumentException("illegal character: "+c);
m = m.multiply(BASE);
}
return result;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment