Skip to content

Instantly share code, notes, and snippets.

@czocher
Last active August 29, 2015 14:09
Show Gist options
  • Save czocher/7f79aaaac80adbb8312e to your computer and use it in GitHub Desktop.
Save czocher/7f79aaaac80adbb8312e to your computer and use it in GitHub Desktop.
Natural Binary Code to Gray Code and Gray Code to Binary
public class GrayUtils {
public static int binaryToGray(int binary) {
return (binary ^ (binary >>> 1));
}
public static int grayToBinary(int gray) {
int binary = 0;
int i = Integer.parseUnsignedInt("80000000", 16);
i >>>= Integer.numberOfLeadingZeros(gray);
binary = i;
for(; i > 0; i>>=1) {
binary |= (gray & i) ^ ((binary & (i << 1)) >>> 1);
}
return binary;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment