diff --git a/src/main/java/com/thealgorithms/bitmanipulation/BitSwap.java b/src/main/java/com/thealgorithms/bitmanipulation/BitSwap.java new file mode 100644 index 00000000..40b3097b --- /dev/null +++ b/src/main/java/com/thealgorithms/bitmanipulation/BitSwap.java @@ -0,0 +1,15 @@ +package com.thealgorithms.bitmanipulation; + +public final class BitSwap { + private BitSwap() { + } + /* + * @brief Swaps the bits at the position posA and posB from data + */ + public static int bitSwap(int data, final int posA, final int posB) { + if (SingleBitOperations.getBit(data, posA) != SingleBitOperations.getBit(data, posB)) { + data ^= (1 << posA) ^ (1 << posB); + } + return data; + } +} diff --git a/src/test/java/com/thealgorithms/bitmanipulation/BitSwapTest.java b/src/test/java/com/thealgorithms/bitmanipulation/BitSwapTest.java new file mode 100644 index 00000000..40de770e --- /dev/null +++ b/src/test/java/com/thealgorithms/bitmanipulation/BitSwapTest.java @@ -0,0 +1,13 @@ +package com.thealgorithms.bitmanipulation; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import org.junit.jupiter.api.Test; +public class BitSwapTest { + @Test + void testHighestSetBit() { + assertEquals(3, BitSwap.bitSwap(3, 0, 1)); + assertEquals(5, BitSwap.bitSwap(6, 0, 1)); + assertEquals(7, BitSwap.bitSwap(7, 1, 1)); + } +}