Last active
November 28, 2017 08:44
-
-
Save pfmiles/ba38945cf33e1022e7f16ef499abc0a0 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
public final class AlphabetEncoder { | |
private static final String[] ALPHABET = { "0", "1", "2", "3", "4", "5", "6", | |
"7", "8", "9", "成", "都", "欢", "迎", | |
"你", "们" }; | |
private static final long ENCODE_LENGTH = ALPHABET.length; | |
private static final Map<String, Integer> idxMap = new HashMap<>(); | |
static { | |
for (int i = 0; i < ALPHABET.length; i++) | |
idxMap.put(ALPHABET[i], i); | |
} | |
public static String encode(long num) { | |
final List<String> list = new ArrayList<>(); | |
do { | |
list.add(ALPHABET[(int) (num % ENCODE_LENGTH)]); | |
num /= ENCODE_LENGTH; | |
} while (num > 0); | |
Collections.reverse(list); | |
return String.join("", list); | |
} | |
public static long decode(final String encoded) { | |
long ret = 0; | |
String c; | |
for (int index = 0; index < encoded.length(); index++) { | |
c = encoded.substring(index, index + 1); | |
ret *= ENCODE_LENGTH; | |
ret += idxMap.get(c); | |
} | |
return ret; | |
} | |
public static void main(String... args) { | |
long n = 3137331; | |
System.out.println(Long.toHexString(n)); | |
System.out.println(encode(n)); | |
System.out.println(decode(encode(n))); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment