plaintext

// My implementation of a very efficient bit permutation (permute 64-bit words using a smaller permutation table)
// take in a byte in 0-255, permute the bits, return the byte with bits permuted.
// Table is normalized to ensure no repeated or omitted values.
byte permuteBits(byte input, const byte table[8]) {
byte output = 0;
for (int i = 0; i < 8; ++i) {
// Shift bits to the left based on the table value (0-7)
// Using bitwise AND to ensure the correct bit is read from the input
output |= ((input >> i) & 1) << (7 – table[i]);
}
return output;
}

Now, to explain the code:

  • We’re using a byte type for both input and output, representing 8 bits.
  • The table is assumed to be an array of 8 bytes, each in the range 0-7, with each number appearing exactly once (a permutation of {0, 1, 2, 3, 4, 5, 6, 7}).
  • We iterate over each bit in the input (from 0 to 7).
    • For each bit, we check its value ((input >> i) & 1 results in either 0 or 1).
    • Then, we shift this 0 or 1 to the position specified by table[i] (7 - table[i] is because we’re treating bit 0 as the LSB and bit 7 as the MSB).
    • We use bitwise OR (|=) to accumulate the shifted bits into output.
  • At the end, output contains the permuted bits as defined by table.

Here’s an example of how the permutation might work:

  • Let’s say input is 0b11010010 (which is 210 in decimal).
  • And our table is {7, 6, 5, 4, 3, 2, 1, 0} (a bit reversal).
    • The bit at position 0 (LSB) is 0, and table[0] is 7. So, (input >> 0) & 1 is 0, and shifted left by 7 - 7 = 0 is 0b0.
    • The bit at position 1 is 1, and table[1] is 6. (input >> 1) & 1 is 1, shifted left by 7 - 6 = 1 is 0b10.
    • … and so on, until:
    • The bit at position 7 is 1, and table[7] is 0. (input >> 7) & 1 is 1, shifted left by 7 - 0 = 7 is 0b10000000.
    • Combining all these, the final output is 0b01001011 (75 in decimal), which is indeed 11010010 reversed.

This is just for demonstration; the table parameter can be any permutation of {0, 1, 2, 3, 4, 5, 6, 7}.

Note that byte is assumed to be an unsigned 8-bit type (unsigned char on many systems). The code ensures that no bits are repeated or omitted in the output because table is a permutation of 0-7. The provided function is straightforward and efficient, as it directly applies the permutation table to the input without redundant checks or complex operations.

vegan chicken substitute

Leave a Reply

Your email address will not be published. Required fields are marked *