| Something probably not particularly important to the author (given that he's just using these essentially as a serial number), but worth mentioning for general use: > Varints can represent negative numbers too, by casting them to unsigned numbers first. But, assuming you're working with twos-complement numbers, it's going to be really inefficient, because small negative numbers are going to end up represented as extremely large positive numbers (e.g. -1 will map to MAX_INT - 1, where MAX_INT is the largest unsigned value representable in your underlying integer type). You also lose the unlimited length property if you need to handle twos-complement integers, and your encoding is dependent on the underlying integer type you're serializing from/deserializing to (especially problematic in languages where types are architecture-dependent, like C/C++). Protobuf handles this by doing what they call "ZigZag encoding" if you declare a value as a signed integer type. This maps small negative numbers to small positive numbers, alternating back and forth like so: Original Encoded
0 0
-1 1
1 2
-2 3
2 4
and so on.The catch is that you lose sortability if you do this... if you're going to have a bunch of negative numbers and need their encoded versions to sort correctly, you'll need to do something else. (Of course, you'll need to with twos-complement numbers, too, given that -1 will appear to be greater than 1). Protobuf documentation on ZigZag encoding: https://developers.google.com/protocol-buffers/docs/encoding... |