From 48ae88f09d595bf6bdd3440b003e08419c885126 Mon Sep 17 00:00:00 2001 From: Lukas <142339568+lukasb1b@users.noreply.github.com> Date: Sun, 15 Oct 2023 09:03:25 +0200 Subject: [PATCH] Bit swap (#4770) * Create BitSwap.java * Create BitSwapTest.java * Update BitSwap.java * Update BitSwap.java * Update BitSwapTest.java * Update BitSwap.java * Update BitSwap.java * Update BitSwapTest.java * Update BitSwapTest.java * Update src/main/java/com/thealgorithms/bitmanipulation/BitSwap.java Co-authored-by: Piotr Idzik <65706193+vil02@users.noreply.github.com> * Update src/test/java/com/thealgorithms/bitmanipulation/BitSwapTest.java Co-authored-by: Piotr Idzik <65706193+vil02@users.noreply.github.com> * Update BitSwap.java * Update BitSwap.java * Update BitSwap.java * Update src/main/java/com/thealgorithms/bitmanipulation/BitSwap.java Co-authored-by: Piotr Idzik <65706193+vil02@users.noreply.github.com> * Update src/main/java/com/thealgorithms/bitmanipulation/BitSwap.java Co-authored-by: Piotr Idzik <65706193+vil02@users.noreply.github.com> * Update src/test/java/com/thealgorithms/bitmanipulation/BitSwapTest.java Co-authored-by: Piotr Idzik <65706193+vil02@users.noreply.github.com> * style: remove redundant blank line --------- Co-authored-by: Piotr Idzik <65706193+vil02@users.noreply.github.com> --- .../thealgorithms/bitmanipulation/BitSwap.java | 15 +++++++++++++++ .../bitmanipulation/BitSwapTest.java | 13 +++++++++++++ 2 files changed, 28 insertions(+) create mode 100644 src/main/java/com/thealgorithms/bitmanipulation/BitSwap.java create mode 100644 src/test/java/com/thealgorithms/bitmanipulation/BitSwapTest.java 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)); + } +}