Home > Back-end >  Push 4 bits into an int in java
Push 4 bits into an int in java

Time:03-22

For an implementation of a SPN crypografic feature (studies related) I'm trying to push 4bits into an int.
I can pinpoint the mistake, but I don't know how to fix it (might stared too long at it for now).

private int applySBox(int a, boolean inverse, boolean verbose) {
    // split int (16 bit) into parts of 4 bit keeping the right order
    int[] parts = new int[4];
    for(int i = 0; i < 4; i  ) {
        parts[4 - i - 1] = a & 0b1111;
        a = a >> 4;
    }

    // Apply the SBox to each 4 bit
    // E.g. 1101 traverse (enc) = 1001, inverse (dec) = 0010
    for(int i = 0; i < 4; i  ) {
        if(inverse) {
            parts[i] = sbox.inverse(parts[i]);
        } else {
            parts[i] = sbox.traverse(parts[i]);
        }
    }

    int result = 0;
    // put back together
    for(int i = 0; i < 4; i  ) {
        result = parts[i] & 0b1111;
        // TODO: Reassigning does not help here, needs shift and &
        result = result << 4;
    }
    return result;
}

Before the SBox I might get a value of 1100111011001111 as cipher text.
In the split portion I get something like this:

Fragment[0]: 0001100011110000
Round Value: 0001100011110000
Current key: 1101011000111111
New r Value: 1100111011001111
---
Before SBox: 1100_1110_1100_1111
Part[0] before SBox: 1100
Part[1] before SBox: 1110
Part[2] before SBox: 1100
Part[3] before SBox: 1111
Part[0] after SBox: 1011
Part[1] after SBox: 0000
Part[2] after SBox: 1011
Part[3] after SBox: 0101

I know this is correct based on the defintion of the SBox I have to use.
This would mean, that in order to get the result I have to push parts 0 to 3 pack into one int 1011_0000_1011_0101 and it would be the correct result.
I can clearly see that it won't work because I always overwrite the result with result = parts[i] & 0b1111; I just can't seem to find a fix.
How can I push an int[] array each int with 4 bits worth of data in the order from 0 to 3 into the int result containing 16 bit of data?

CodePudding user response:

If you shift the bits to the left then the rightmost bits fill up with zeros. So then you need to XOR or OR the results into place.

Try and replace

result = parts[i] & 0b1111;

with

result ^= parts[i] & 0b1111;

or

result |= parts[i] & 0b1111;

otherwise you are simply reassigning the value and delete the previous 4 bit blocks.

CodePudding user response:

Do you mean:

result = (result << 4) & parts[i];

or, same thing written differently:

result &= parts[i] << (4 * (4-i));

If so then, yes, you stared too long at the screen and "got square eyes" as they say!

  • Related