From 115ed2efbf0d97140bfbdd96f2e583835868e8d9 Mon Sep 17 00:00:00 2001 From: Sebastian Hugentobler Date: Thu, 17 Mar 2022 17:59:32 +0100 Subject: [PATCH] implement bit swapping --- src/main/java/ch/fhnw/kry/SPN.java | 17 ++++------------- src/test/java/ch/fhnw/kry/SPNTest.java | 6 ++++-- 2 files changed, 8 insertions(+), 15 deletions(-) diff --git a/src/main/java/ch/fhnw/kry/SPN.java b/src/main/java/ch/fhnw/kry/SPN.java index b17ea73..cbcbfd2 100644 --- a/src/main/java/ch/fhnw/kry/SPN.java +++ b/src/main/java/ch/fhnw/kry/SPN.java @@ -62,20 +62,11 @@ public class SPN { } public int swapBits(int x, int a, int b) { - int tmpA = (x & (0x1 << (15 - a))); - int tmpB = (x & (0x1 << (15 - b))); - - tmpA = tmpA == 0 ? 0 : 1; - tmpB = tmpB == 0 ? 0 : 1; + a = 15 - a; + b = 15 - b; - tmpA = tmpA << (15 -b); - tmpB = tmpB << (15 - a); - - x = x | tmpA; - x = x | tmpB; - - // x = tmpA == 0 ? (x & 0x1 << 15 - b) | 0b0 : (x & 0x1 << 15 - b) | ~0b0; - // x = tmpB == 0 ? (x & 0x1 << 15 - a) | 0b0 : (x & 0x1 << 15 - a) | ~0b0; + x ^= (1 << a); + x ^= (1 << b); return x; } diff --git a/src/test/java/ch/fhnw/kry/SPNTest.java b/src/test/java/ch/fhnw/kry/SPNTest.java index 63952b1..83dd4eb 100644 --- a/src/test/java/ch/fhnw/kry/SPNTest.java +++ b/src/test/java/ch/fhnw/kry/SPNTest.java @@ -43,11 +43,13 @@ class SPNTest { int r = 0xC; // when - int y = spn.swapBits(x, 1, 2); - int yy = spn.swapBits(x, 2, 1); + int y = spn.swapBits(x, 13, 14); + int yy = spn.swapBits(x, 14, 13); + int yyy = spn.swapBits(x, 14, 14); // then assertEquals(r, y); assertEquals(r, yy); + assertEquals(x, yyy); } }