1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113
| import java.util.Random;
public class ShareCodeUtil {
private static final char[] BASE = new char[] { 'H', 'V', 'E', '8', 'S', '2', 'D', 'Z', 'X', '9', 'C', '7', 'P', '5', 'I', 'K', '3', 'M', 'J', 'U', 'F', 'R', '4', 'W', 'Y', 'L', 'T', 'N', '6', 'B', 'G', 'Q' };
private static final char SUFFIX_CHAR = 'A';
private static final int BIN_LEN = BASE.length;
private static final int CODE_LEN = 6;
public static String idToCode(Long id) { char[] buf = new char[BIN_LEN]; int charPos = BIN_LEN;
while (id / BIN_LEN > 0) { int index = (int) (id % BIN_LEN); buf[--charPos] = BASE[index]; id /= BIN_LEN; }
buf[--charPos] = BASE[(int) (id % BIN_LEN)]; String result = new String(buf, charPos, BIN_LEN - charPos);
int len = result.length(); if (len < CODE_LEN) { StringBuilder sb = new StringBuilder(); sb.append(SUFFIX_CHAR); Random random = new Random(); for (int i = 0; i < CODE_LEN - len - 1; i++) { sb.append(BASE[random.nextInt(BIN_LEN)]); }
result += sb.toString(); }
return result; }
public static Long codeToId(String code) { char[] charArray = code.toCharArray(); long result = 0L; for (int i = 0; i < charArray.length; i++) { int index = 0; for (int j = 0; j < BIN_LEN; j++) { if (charArray[i] == BASE[j]) { index = j; break; } }
if (charArray[i] == SUFFIX_CHAR) { break; }
if (i > 0) { result = result * BIN_LEN + index; } else { result = index; } }
return result;
}
public static void main(String[] args) { String code = idToCode(1L); System.out.println(code); System.out.println(codeToId(code)); }
}
|