シリアル番号の生成を再生する別の方法-62ベースを再生する方法は?

通常、一意のシリアル番号を生成するときは、時間をシリアル番号として使用しますが、時間のシリアル番号の長さは15に、userid、merchantidなどの他のものを加えたものです。長さは50〜60桁に達し、シリアル番号になります。ロングリード。

シリアル番号の生成を再生する別の方法-62ベースを再生する方法は?

1.保管時に多くのスペースを占有します。

2.クエリ中の効率が遅い

時系列番号を短くできますか?

私たちは知っています:

ascIIコーディングテーブルによると:

異なるストレージを使用する場合の小文字のa(97)エンコード長

バイナリ:01100001

オクタル:141

10進数:97

ヘキサデシマル:61

ベースが大きくなると、文字の長さがどんどん短くなっていくことがわかります.62文字を取ると、コードとして0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZを使用するのが一般的です。

コーディングする前に、gitを検索しました。上記のコードは実装されています(base62)。再度実装することはありません。コードは次のとおりです。

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.デコード、逆プロセス

 /**
 * 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;
 }

テストケース(例として15桁のタイムスタンプを使用):

 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));
 }

コンソール出力は次のとおりです。

2OdCqJOH8
613534552694770
613534552694770

長さが15桁から9桁に変更され、長さが40%短縮され、それに応じて現在のクエリ効率が向上しました。

おもしろくないですか?

おすすめ

転載: blog.51cto.com/15015181/2556407