一些读者可能会对LEB128有用的原因感兴趣.如果大多数时候数字的大小相对较小,它提供一种表示数字的压缩.即使在随机输入上,平均而言,它将使用8个字节中的5个来表示64位数字(尽管最坏的情况下,它将使用10个字节).
以下是对无符号64位数进行编码和解码的实现.我会留下签名版本作为感兴趣的读者的练习.
size_t fwrite_uleb128 (FILE *out, uint64_t x) {
unsigned char buf[10];
size_t bytes = 0;
do {
buf[bytes] = x & 0x7fU;
if (x >>= 7) buf[bytes] |= 0x80U;
++bytes;
} while (x);
return fwrite(buf, bytes, 1, out);
}
size_t fread_uleb128 (FILE *in, uint64_t *x) {
unsigned char buf;
size_t bytes = 0;
while (fread(&buf, 1, 1, in)) {
if (bytes == 0) *x = 0;
*x |= (buf & 0x7fULL) << (7 * bytes++);
if (!(buf & 0x80U)) break;
}
return !!bytes;
}