ZigZag Encoding
Created on 2023-06-20T00:35:21-05:00
What
Numbers are interleaved so that negative and positive numbers all share a positive space. For example the number line becomes this: 0, 1, -1, 2, -2, 3, -3, and so on
If a coding scheme does not support negative numbers but you need it to, this is what you use.
Why
Used by Protocol Buffers to store numbers which may be negative or positive.
I don't know why they use them though. CBOR and others just have a negative integer type which gets around having to encode the flag bit.
How
sint32: (n << 1) ^ (n >> 31)
sint64: (n << 1) ^ (n >> 63)
Second shift is arithmetic/circular. In Nim its easiest to pull in C code via emit.