Some Name
Some Name

Reputation: 9540

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"?

Upvotes: 0

Views: 1134

Answers (1)

NiVeR
NiVeR

Reputation: 9796

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);

Upvotes: 1

Related Questions