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