Skip to content

Instantly share code, notes, and snippets.

@JohnKim
Created March 5, 2014 14:39
Show Gist options
  • Save JohnKim/9368423 to your computer and use it in GitHub Desktop.
Save JohnKim/9368423 to your computer and use it in GitHub Desktop.
Bijective
public class BijectiveUtils {
private static final String ALPHABET = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
private static final int BASE = 62;
public static String encode(int num) {
StringBuilder sb = new StringBuilder();
while ( num > 0 ) {
sb.append( ALPHABET.charAt( num % BASE ) );
num /= BASE;
}
return sb.reverse().toString();
}
public static int decode(String str) {
int num = 0;
for ( int i = 0, len = str.length(); i < len; i++ ) {
num = num * BASE + ALPHABET.indexOf( str.charAt(i) );
}
return num;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment