Lucene VInt学习

VINT 类型lucene给出了定义是一个可变长度的byte组合来表示一个正整数

   VInt lucene给出了一个例子表格

 

Value

First byte

Second byte

Third byte

0

00000000

 

 

1

00000001

 

 

2

00000010

 

 

...

 

 

 

127

01111111

 

 

128

10000000

00000001

 

129

10000001

00000001

 

130

10000010

00000001

 

...

 

 

 

16,383

11111111

01111111

 

16,384

10000000

10000000

00000001

16,385

10000001

10000000

00000001

看表格里的数据意思就是一个byte 表示0-127的整数 如果次数<=127那么只占用一个byte,如果>127则会追加byte来存储此整数的值,那么第一个byte和第二个byte的关系和规则是什么呢 看表格中的表示形式貌似是如果此byte不够表示的话那么将当前byte的二进制中的头位变1,这样一来就没有符号位的表示了,首位0说明只有一个byte首位1则说明后续还有byte来存储此数字。看看lucene的代码中是如果来存储一个int数字为一个VInt类型的可变的byte的吧

/** Writes an int in a variable-length format.  Writes between one and  
   * five bytes.  Smaller values take fewer bytes.  Negative numbers are not  
   * supported.  
   * @see IndexInput#readVInt()  
   */  
  public void writeVInt(int i) throws IOException {   
    while ((i & ~0x7F) != 0) {   
      writeByte((byte)((i & 0x7f) | 0x80));   
      i >>>= 7;   
    }   
    writeByte((byte)i);   
  }  

 

 看看这样移位以后再读取的时候lucene的反向移位运算代码

 

/** Reads an int stored in variable-length format.  Reads between one and  
   * five bytes.  Smaller values take fewer bytes.  Negative numbers are not  
   * supported.  
   * @see IndexOutput#writeVInt(int)  
   */  
  public int readVInt() throws IOException {   
    byte b = readByte();   
    int i = b & 0x7F;   
    for (int shift = 7; (b & 0x80) != 0; shift += 7) {   
      b = readByte();   
      i |= (b & 0x7F) << shift;   
    }   
    return i;   
  }  

 

 

摘录自 http://blog.csdn.net/a276202460/archive/2010/06/01/5640983.aspx

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值