Last active
December 30, 2019 18:29
-
-
Save fabri1983/b8b0889ff2e09434f1e8442c2ec9fe3f to your computer and use it in GitHub Desktop.
Encoded a 10 max length String with up to 64 different characters (using 6 bits per character) in a long type (64 bits).
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
/** | |
* Encoding a string into a long. | |
* <br/> | |
* Squeeze a String inside a long type, although we need to accept some limitations. | |
* <br/> | |
* The long type has 64 bits, so using a base 64 encoding (6 bits) we can store up to 10 characters inside. | |
* <br/> | |
* We assume that the target String has a maximum length of 10 characters and they are composed only | |
* of uppercase letters, numbers and a limited number of special characters. | |
*/ | |
public class MiniString { | |
long raw; | |
public MiniString(String str) { | |
raw = encode(str); | |
} | |
public String get() { | |
return decode(raw); | |
} | |
public static final int MAX_MINISTR_LEN = 10; | |
public static final int MINI_STR_BASE = 64; | |
public static final String letters = "=ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 _-!?.$&%@#:[]{}()*<>:;',/^"; | |
public static long encode(String str) { | |
String prepared = prepareString(str); | |
long encoded = 0; | |
for (char c : prepared.toCharArray()) { | |
int x = letters.indexOf(c); | |
encoded = encoded * MINI_STR_BASE + x; | |
} | |
return encoded; | |
} | |
private static String prepareString(String str) { | |
StringBuilder prepared = new StringBuilder(); | |
for (char c : str.toCharArray()) { | |
if (letters.indexOf(c) >= 0) | |
prepared.append(c); | |
if (prepared.length() > MAX_MINISTR_LEN) | |
break; | |
} | |
return prepared.toString(); | |
} | |
public static String decode(long number) { | |
StringBuilder decoded = new StringBuilder(); | |
long remaining = number; | |
while (true) { | |
int mod = (int) (remaining % MINI_STR_BASE); | |
char c = letters.charAt(mod); | |
decoded.insert(0, c); | |
if (remaining < MINI_STR_BASE) | |
break; | |
remaining = remaining / MINI_STR_BASE; | |
} | |
return decoded.toString(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment