Search code examples
javalong-integerzigzag-encoding

ZigZag decode/encode in Java


I'm looking for some library which can provide with the functions that can help deconding zig-zag encoded byte array into 2's complement long/int and back.

Since ZigZag is used in protobuf I expected that guava has something for it, but googling did not give any result. By ZigZag encoding I mean this:

Signed Original Encoded As
0               0
-1              1
1               2
-2              3
2147483647      4294967294
-2147483648     4294967295

Do I have to "reinvent the wheel"?


Solution

  • Here you go:

        Long aD = 2147483647L;
        //encode
        Long aE = (aD >> 31) ^ (aD << 1);
        //decode
        Long bD = (aE >> 1) ^ -(aE & 1);
    
        System.out.println(aD + "," + aE + "," + bD);