为什么在 Thrift CompactProtocol 中以可变长度编码交换字节?

Why swap bytes in variable length encoding in the Thrift CompactProtocol?

我想知道为什么在编码具有可变长度的 Int 时必须在 Trift CompactProtocol 中交换字节。

示例取自 Data Intensive Applications(在线,第 120 页):

Number in Base 10 to be encoded: 1337
1337 in Base 2: 0010100 111001
Encoding first byte:  1|111011|0
Encoding second byte: 0|0010100

如您所见,字节已被交换。这是为什么?

附加信息:第一个字节中的第一个位表示还有一个字节要来。第一个字节中的最后一位代表符号(在本例中为正)。最后一个符号中的第一位表示没有更多的额外字节属于这个数字。

这是一种对小整数进行编码的有效方法,或者更准确地说,是对小 绝对 值进行编码。这个想法在protobuf documentation中解释的很好:

ZigZag encoding maps signed integers to unsigned integers so that numbers with a small absolute value (for instance, -1) have a small varint encoded value too. It does this in a way that "zig-zags" back and forth through the positive and negative integers, so that -1 is encoded as 1, 1 is encoded as 2, -2 is encoded as 3, and so on, as you can see in the following table [...]

小的绝对值很常见 case.Large 值很少。因此,对于大多数用例,我们会携带大量(不必要的)零而没有附加值。不幸的是,对于负值,它有点复杂,因为我们必须关心符号位。

ZigZag 算法以一种非常优雅和非常有效的方式解决了这个问题。