implement bit swapping

This commit is contained in:
Sebastian Hugentobler 2022-03-17 17:59:32 +01:00
parent a399de663f
commit 115ed2efbf
2 changed files with 8 additions and 15 deletions

View File

@ -62,20 +62,11 @@ public class SPN {
} }
public int swapBits(int x, int a, int b) { public int swapBits(int x, int a, int b) {
int tmpA = (x & (0x1 << (15 - a))); a = 15 - a;
int tmpB = (x & (0x1 << (15 - b))); b = 15 - b;
tmpA = tmpA == 0 ? 0 : 1;
tmpB = tmpB == 0 ? 0 : 1;
tmpA = tmpA << (15 -b); x ^= (1 << a);
tmpB = tmpB << (15 - a); x ^= (1 << b);
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;
return x; return x;
} }

View File

@ -43,11 +43,13 @@ class SPNTest {
int r = 0xC; int r = 0xC;
// when // when
int y = spn.swapBits(x, 1, 2); int y = spn.swapBits(x, 13, 14);
int yy = spn.swapBits(x, 2, 1); int yy = spn.swapBits(x, 14, 13);
int yyy = spn.swapBits(x, 14, 14);
// then // then
assertEquals(r, y); assertEquals(r, y);
assertEquals(r, yy); assertEquals(r, yy);
assertEquals(x, yyy);
} }
} }