github.com/egonelbre/exp@v0.0.0-20240430123955-ed1d3aa93911/bit/zigzag.go (about) 1 package bit 2 3 // ZEncode implements zig-zag encoding 4 // The sign will be encoded as the least significant bit in the result 5 // ZEncode(x) < abs(x)*2 6 func ZEncode(x int64) uint64 { 7 return uint64((x << 1) ^ (x >> 63)) 8 } 9 10 // ZDecode is the inverse operation of ZEncode 11 // ZDecode(ZEncode(x)) == x 12 func ZDecode(ux uint64) int64 { 13 //TODO: optimize 14 if ux&1 == 1 { 15 return -int64(ux>>1 + 1) 16 } 17 return int64(ux >> 1) 18 }