Created
January 7, 2017 19:57
-
-
Save hikilaka/01fe0413a49d7a41ef0a280084076d59 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
/** | |
* Encodes a string into its base37 integral value | |
* | |
* @param str the string to encode | |
* @return the base37 value | |
*/ | |
public static long encodeb37(String str) { | |
String str1 = ""; | |
for (int i = 0; i < str.length(); i++) { | |
char c = str.charAt(i); | |
if (c >= 'a' && c <= 'z') | |
str1 = str1 + c; | |
else if (c >= 'A' && c <= 'Z') | |
str1 = str1 + (char)((c + 97) - 65); | |
else if (c >= '0' && c <= '9') | |
str1 = str1 + c; | |
else | |
str1 = str1 + ' '; | |
} | |
str1 = str1.trim(); | |
if(str1.length() > 12) | |
str1 = str1.substring(0, 12); | |
long base = 0L; | |
for (int i = 0; i < str1.length(); i++) { | |
char c1 = str1.charAt(i); | |
base *= 37L; | |
if (c1 >= 'a' && c1 <= 'z') | |
base += (1 + c1) - 97; | |
else if(c1 >= '0' && c1 <= '9') | |
base += (27 + c1) - 48; | |
} | |
return base; | |
} | |
/** | |
* Decodes a base37 integral value into a string | |
* | |
* @param base the base37 value | |
* @return the decoded string value | |
*/ | |
public static String decodeb37(long base) { | |
if(base < 0L) | |
return "invalid_name"; | |
String str = ""; | |
while(base != 0L) { | |
int value = (int)(base % 37L); | |
base /= 37L; | |
if (value == 0) | |
str = " " + str; | |
else if (value < 27) { | |
if (base % 37L == 0L) | |
str = (char)((value + 65) - 1) + str; | |
else | |
str = (char)((value + 97) - 1) + str; | |
} else { | |
str = (char)((value + 48) - 27) + str; | |
} | |
} | |
return str; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment