在查看相对较大的现有代码库的代码时,我发现了以下函数:
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个字节)。这些有效的假设是什么?
我想制作一个read_actual_size版本......我能不能每个字节直线“向右移7”直到我遇到“0”?
请不要非常苛刻,我是C的新手。
答案 0 :(得分:2)
通用VLQ解码器看起来像这样:
int decode_vlq(unsigned char *input)
{
int result = 0;
do
{
result = (result << 7) | (*input & 0x7F);
}
while (*input++ & 0x80);
return result;
}
我愿意接受建议,因为我的C很生锈,而且我是手工写的。