Skip to content

Instantly share code, notes, and snippets.

@heminy
Last active June 7, 2018 11:24
Show Gist options
  • Save heminy/7dded9e44743b3df854809db20ae5806 to your computer and use it in GitHub Desktop.
Save heminy/7dded9e44743b3df854809db20ae5806 to your computer and use it in GitHub Desktop.
base62 for Java
public static final String CODES = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
public static String toBase62(int value) {
final StringBuilder sb = new StringBuilder(1);
do {
sb.insert(0, CODES.charAt(value % 62));
value /= 62;
} while (value > 0);
return sb.toString();
}
public static long toBase10(String value) {
value = new StringBuffer(value).reverse().toString();
int ret = 0;
int count = 1;
for (char character : value.toCharArray()) {
ret += CODES.indexOf(character) * count;
count *= 62;
}
return ret;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment