1

在查看一个比较大的现有代码库的代码时,我发现了以下函数:

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很陌生。

4

1 回答 1

2

一个通用的VLQ解码器看起来像这样:

int decode_vlq(unsigned char *input)
{
    int result = 0;
    do
    {
        result = (result << 7) | (*input & 0x7F);
    }
    while (*input++ & 0x80);
    return result;
}

我愿意接受建议,因为我的 C 很生锈,而且我是手写的。

于 2013-06-15T20:08:03.440 回答