当查看一个相对大的现有代码库的代码时,我发现以下函数:
int write_actual_size(unsigned int actual_size, int &out_size)
{
unsigned char second;
unsigned char third;
unsigned char fourth;
int result;
int usedBytes;
*(unsigned char *)out_size = actual_size | 0x80;
if ( actual_size < 0x80 ) {
*(unsigned char *)out_size = ((unsigned char)actual_size | 0x80) & 0x7F;
result = 1;
} else {
second = (actual_size >> 7) | 0x80;
*(unsigned char *)(out_size + 1) = second;
if (actual_size < 0x4000) {
*(unsigned char *)(out_size + 1) = second & 0x7F;
usedBytes = 2;
} else {
third = (actual_size >> 14) | 0x80;
*(unsigned char *)(out_size + 2) = third;
if (actual_size < 0x200000) {
*(unsigned char *)(out_size + 2) = third & 0x7F;
usedBytes = 3;
}
else {
fourth = (actual_size >> 21) | 0x80;
*(unsigned char *)(out_size + 3) = fourth;
if (actual_size < 0x10000000) {
*(unsigned char *)(out_size + 3) = fourth & 0x7F;
usedBytes = 4;
}
}
}
result = usedBytes;
}
return result;
}
这会根据原始输入大小,将普通无符号整数编码为一个或多个字节。
据我所知,最左边的位用于确定是否有“后续”字节。我假设这样做的原因是为了节省带宽(即使每个包最多3个字节)。这些假设有效吗?
我想做一个实际尺寸的版本。。。我可以每字节线性地“右移7”直到遇到一个“0”吗?
请不要太苛刻,我对C很陌生。
最佳答案
一般的VLQ解码器看起来像这样:
int decode_vlq(unsigned char *input)
{
int result = 0;
do
{
result = (result << 7) | (*input & 0x7F);
}
while (*input++ & 0x80);
return result;
}
我很乐意接受建议,因为我的C已经很生疏了,我是亲手写的。