3 ms·
One of the coolest XOR tricks I've seen is fast encoding of negative integers to positive integers (unsigned) employed by ProtoBufs. It is called ZigZag encodin
by ignoramous 6y ago
One of the coolest XOR tricks I've seen is fast encoding of negative integers to positive integers (unsigned) employed by ProtoBufs. It is called ZigZag encoding where negative and positive integers are interleaved such that lower negative values are assigned to lower positive values:
input zz(int)
0 0
1 2
2 4
3 6
-1 1
-2 3
zz(n int64) => (n << 1) ^ (n >> 63)
unzz(n int64) => (n >> 1) ^ (-(n & 0x1))
https://developers.google.com/protocol-buffers/docs/encoding?csw=1#types https://developers.google.com/protocol-buffers/docs/encoding...
Edit: Fixed unzz, ref: https://github.com/lemire/FastIntegerCompression.js/blob/033768f72/FastIntegerCompression.js#L44-L46 https://github.com/lemire/FastIntegerCompression.js/blob/033...
- user-the-name 6y agounzz does not look correct there. Edit: Looks good now!
- ufo 6y agoDoesn't a bitwise OR work just as well as a XOR here?