Skip to content

Instantly share code, notes, and snippets.

@matancev
Created January 24, 2014 16:25
Show Gist options
  • Select an option

  • Save matancev/8600694 to your computer and use it in GitHub Desktop.

Select an option

Save matancev/8600694 to your computer and use it in GitHub Desktop.
class Base62 {
public Base62(BigInteger num) {
base62 = setBase62FromString(num);
}
public String setBase62FromString(BigInteger num) {
StringBuilder builder = new StringBuilder();
BigInteger modRes;
BigInteger n62 = new BigInteger("62");
do {
modRes = num.mod(n62);
builder.insert(0, alphabet.charAt(modRes.intValue()));
num = num.divide(n62);
if(num.compareTo(n62) == -1) {
builder.insert(0, alphabet.charAt(num.intValue()));
}
} while(num.compareTo(n62) == 1);
return builder.toString();
}
public BigInteger toBigInteger() {
BigInteger result = new BigInteger("0");
int b = 0;
for(int i = base62.length()-1; i != -1; i--) {
int decValue = alphabet.indexOf(base62.charAt(b));
BigInteger next = new BigInteger(
String.valueOf(
(int)(decValue * Math.pow(62.0, i))
)
);
result = result.add(next);
b += 1;
}
return result;
}
public String toString() {
return base62;
}
private String base62;
private final String alphabet = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment