// 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
bytetype for both input and output, representing 8 bits. - The
tableis assumed to be an array of 8 bytes, each in the range0-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) & 1results in either0or1). - Then, we shift this
0or1to the position specified bytable[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 intooutput.
- For each bit, we check its value (
- At the end,
outputcontains the permuted bits as defined bytable.
Here’s an example of how the permutation might work:
- Let’s say
inputis0b11010010(which is210in decimal). - And our
tableis{7, 6, 5, 4, 3, 2, 1, 0}(a bit reversal).- The bit at position 0 (LSB) is
0, andtable[0]is7. So,(input >> 0) & 1is0, and shifted left by7 - 7 = 0is0b0. - The bit at position 1 is
1, andtable[1]is6.(input >> 1) & 1is1, shifted left by7 - 6 = 1is0b10. - … and so on, until:
- The bit at position 7 is
1, andtable[7]is0.(input >> 7) & 1is1, shifted left by7 - 0 = 7is0b10000000. - Combining all these, the final
outputis0b01001011(75in decimal), which is indeed11010010reversed.
- The bit at position 0 (LSB) is
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