add bit string to int array conversion

This commit is contained in:
Sebastian Hugentobler 2022-03-21 09:38:13 +01:00
parent 1fd74c6ec3
commit 55876a7d33
Signed by: shu
GPG Key ID: BB32CF3CA052C2F0
2 changed files with 35 additions and 0 deletions

View File

@ -67,6 +67,29 @@ public class SPN {
return null;
}
/**
* Convert a bit string into an integer array.
*
* Because later we only ever look at the lower 16 bits,
* we stuff every block of 16 bits into the lower half of an int
* (meaning the igh 16 bits of the ints in the array are always 0).
*
* @param bits Bit string. Its length must be a multiple of 16.
* @return int array, with every int's lower 16 bits set to 16 bits of the input string.
*/
public int[] strToArray(String bits) {
int[] data = new int[bits.length() / 16];
for (int i = 0; i < data.length; i++) {
int startIdx = i * 16;
String wordBits = bits.substring(startIdx, startIdx + 16);
int word = Integer.parseInt(wordBits, 2);
data[i] = word;
}
return data;
}
/**
* Encrypt a block with the defined SPN.
*

View File

@ -73,4 +73,16 @@ class SPNTest {
assertEquals(y, spn.encryptBlock(key, x));
assertEquals(x, spn.decryptBlock(key, y));
}
@Test
void strToArray() {
var spn = new SPN();
String input = "00000100110100100000101110111000000000101000111110001110011111110110000001010001010000111010000000010011011001110010101110110000";
int[] data = spn.strToArray(input);
assertEquals(8, data.length);
assertEquals(0x04D2, data[0]);
assertEquals(0x2BB0, data[data.length - 1]);
}
}