Another way to play the serial number generation-how to play 62 base?

Usually when we generate a unique serial number, we like to use the time as the serial number, but the length of the time serial number is 15, plus other such as userid, merchantid, etc. The length reaches 50-60 digits, which leads to our serial number. Long lead.

Another way to play the serial number generation-how to play 62 base?

1. It takes up a lot of space when stored,

2. Slow efficiency during query

Can we shorten the time series number?

we know:

According to ascII coding table:

Lowercase character a(97) encoding length when using different storage

Binary: 01100001

Octal: 141

Decimal: 97

Hexadecimal: 61

It can be seen that with the increase of the base, the length of the characters will become shorter and shorter. If we take the 62 characters we commonly use 0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ as the code, then the 62 base can be expressed.

Before coding, I searched git. The above code has been implemented (base62), I will not implement it again, the code is as follows:

1.编码,将long型转换为62进制字符串

 /**
 * Encodes a decimal value to a Base62 <code>String</code>.
 *
 * @param b10
 * the decimal value to encode, must be nonnegative.
 * @return the number encoded as a Base62 <code>String</code>.
 */
 public String encodeBase10(long b10) {
 if (b10 < 0) {
 throw new IllegalArgumentException("b10 must be nonnegative");
 }
 String ret = "";
 while (b10 > 0) {
 ret = characters.charAt((int) (b10 % 62)) + ret;
 b10 /= 62;
 }
 return ret;

 }

2. Decoding, reverse process

 /**
 * Decodes a Base62 <code>String</code> returning a <code>long</code>.
 *
 * @param b62
 * the Base62 <code>String</code> to decode.
 * @return the decoded number as a <code>long</code>.
 * @throws IllegalArgumentException
 * if the given <code>String</code> contains characters not
 * specified in the constructor.
 */
 public long decodeBase62(String b62) {
 for (char character : b62.toCharArray()) {
 if (!characters.contains(String.valueOf(character))) {
 throw new IllegalArgumentException("Invalid character(s) in string: " + character);
 }
 }
 long ret = 0;
 b62 = new StringBuffer(b62).reverse().toString();
 long count = 1;
 for (char character : b62.toCharArray()) {
 ret += characters.indexOf(character) * count;
 count *= 62;
 }
 return ret;
 }

Test case (take 15-digit timestamp as an example):

 public static void main(String[] args) {
 Base62 encoder=new Base62();
 Long time=System.nanoTime();
 String timeStr=encoder.encodeBase10(time);
 System.out.println(timeStr);

 System.out.println(time);
 System.out.println(encoder.decodeBase62(timeStr));
 }

The console output is as follows:

2OdCqJOH8
613534552694770
613534552694770

The length is changed from 15 digits to 9 digits, which reduces the length by 40%, and the current query efficiency has been correspondingly improved.

Isn’t it interesting?

Guess you like

Origin blog.51cto.com/15015181/2556407
Recommended