leveldb 采用 protocalbuffer 里使用的变长整形编码方案,以节省空间;
一个byte分成两部分:最高1个bit 和 剩余7个bit;
最高1个bit 以用来表示 剩余7个bit 是否能装下uint32;
读源码一目了然:
代码语言:javascript复制//leveldb-master/util/coding.cc
char* EncodeVarint32(char* dst, uint32_t v) {
// Operate on characters as unsigneds
unsigned char* ptr = reinterpret_cast<unsigned char*>(dst);
static const int B = 128;
if (v < (1<<7)) {
*(ptr ) = v;
} else if (v < (1<<14)) {
*(ptr ) = v | B;
*(ptr ) = v>>7;
} else if (v < (1<<21)) {
*(ptr ) = v | B;
*(ptr ) = (v>>7) | B;
*(ptr ) = v>>14;
} else if (v < (1<<28)) {
*(ptr ) = v | B;
*(ptr ) = (v>>7) | B;
*(ptr ) = (v>>14) | B;
*(ptr ) = v>>21;
} else {
*(ptr ) = v | B;
*(ptr ) = (v>>7) | B;
*(ptr ) = (v>>14) | B;
*(ptr ) = (v>>21) | B;
*(ptr ) = v>>28;
}
return reinterpret_cast<char*>(ptr);
}