File tree Expand file tree Collapse file tree
main/java/com/thealgorithms/bitmanipulation
test/java/com/thealgorithms/bitmanipulation Expand file tree Collapse file tree Original file line number Diff line number Diff line change 22
33/**
44 * Gray code is a binary numeral system where two successive values differ in only one bit.
5- * This is a simple conversion between binary and Gray code .
5+ * Each input and result is treated as a 32-bit pattern, including the sign bit .
66 * Example:
77 * 7 -> 0111 -> 0100 -> 4
88 * 4 -> 0100 -> 0111 -> 7
@@ -24,7 +24,7 @@ private GrayCodeConversion() {
2424 * @return The corresponding Gray code.
2525 */
2626 public static int binaryToGray (int num ) {
27- return num ^ (num >> 1 );
27+ return num ^ (num >>> 1 );
2828 }
2929
3030 /**
@@ -35,8 +35,8 @@ public static int binaryToGray(int num) {
3535 */
3636 public static int grayToBinary (int gray ) {
3737 int binary = gray ;
38- while (gray > 0 ) {
39- gray >>= 1 ;
38+ while (gray != 0 ) {
39+ gray >>> = 1 ;
4040 binary ^= gray ;
4141 }
4242 return binary ;
Original file line number Diff line number Diff line change @@ -20,6 +20,18 @@ public void testGrayToBinary() {
2020 assertEquals (1 , GrayCodeConversion .grayToBinary (1 )); // 001 -> 001
2121 }
2222
23+ @ Test
24+ public void testBinaryToGrayWithHighBitSet () {
25+ assertEquals (0x80000000 , GrayCodeConversion .binaryToGray (0xFFFFFFFF ));
26+ assertEquals (0xC0000000 , GrayCodeConversion .binaryToGray (0x80000000 ));
27+ }
28+
29+ @ Test
30+ public void testGrayToBinaryWithHighBitSet () {
31+ assertEquals (0xFFFFFFFF , GrayCodeConversion .grayToBinary (0x80000000 ));
32+ assertEquals (0x80000000 , GrayCodeConversion .grayToBinary (0xC0000000 ));
33+ }
34+
2335 @ Test
2436 public void testBinaryGrayCycle () {
2537 int binary = 9 ; // 1001 in binary
You can’t perform that action at this time.
0 commit comments