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) {
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;
}

View File

@ -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);
}
}