Last active
August 29, 2015 14:09
-
-
Save czocher/7f79aaaac80adbb8312e to your computer and use it in GitHub Desktop.
Natural Binary Code to Gray Code and Gray Code to Binary
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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