Created
March 5, 2014 14:39
-
-
Save JohnKim/9368423 to your computer and use it in GitHub Desktop.
Bijective
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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