Lucene的Vint類型詳解

來源:互聯網
上載者:User

標籤:Lucene   io   ar   for   sp   div   on   代碼   amp   

Lucene Vint壓縮策略是,用每個位元組的最高位做標誌位,後7位為有效算術位,如果標誌位為1,則說明後一個位元組和當前位元組是同一個數字,為0說明後一個位元組是一個新的數字

Lucene原始碼中進行儲存和讀取是這樣的。OutputStream是負責寫:

 1   /** Writes an int in a variable-length format.  Writes between one and
 2    * five bytes.  Smaller values take fewer bytes.  Negative numbers are not
 3    * supported.
 4    * @see InputStream#readVInt()
 5    */
 6   public final void writeVInt(int i) throws IOException {
 7     while ((i & ~0x7F) != 0) {
 8       writeByte((byte)((i & 0x7f) | 0x80));
 9       i >>>= 7;
10     }
11     writeByte((byte)i);
12   }

writeVint(壓縮)步驟

1. i & ~0x7F

   用int i的最低位byte和~0x7F(1000 0000)做與操作,如果為真則說明這個int在等於或者大於第8位的bit上依然還有有效bit,這些bit應該在後面的writeByte操作在寫入(每次迴圈一個位元組包括int的低位7個bit位和一個標誌位)

2 writeByte((byte)((i & 0x7f) | 0x80));

  寫入一個byte,友i的最低7個bit位和一個標誌位(置1)組成

3  i >>>= 7;

   由於寫入了7個bit位,所以i右移7位,使得後面的bit參與下一次寫入

 

4   writeByte((byte)i);

   如果迴圈結束,則說明i剩下的有效bit等於或者小於7位,則當前這次是最後一次writeByte,這時候第8位也不需要置1,直接寫入這個byte皆可。

 ==============================================================================================================================================


InputStream負責讀

 public final int readVInt() throws IOException {
 7     byte b = readByte();
 8     int i = b & 0x7F;
 9     for (int shift = 7; (b & 0x80) != 0; shift += 7) {
10       b = readByte();
11       i |= (b & 0x7F) << shift;
12     }
13     return i;
14   }

1   byte b = readByte(); 

     先讀取低位的一個byte

2    int i = b & 0x7F;

     取這個位元組的低7位(有效數字位)賦值給i

3    for (int shift = 7; (b & 0x80) != 0; shift += 7)

     迴圈先判定當前byte(b)的第8位是不是為1,如果是1,則說明後面還有byte也是屬於這個int, shift是表示當前b裡的有效7位在i裡面對於的bit位置,因為在迴圈開始就已經賦值過7bit,所以shift迴圈開始就從7開始算

 

Lucene的Vint類型詳解

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.