Since C’s bitwise operators &, |, and ~ are typically also assembly language opcodes as well, bit masking code should in principle be very quick.
I’ve got some choices of how I add bit-masking inside the inner loop of a simulation algorithm. Essentially it boils down to the choice between using an array of pre-canned masks, or changing masks dynamically using left and right shifts.
Are there particular tricks / techniques to keep bit-masking as free from unnecessary overhead as possible? Are any of the three approaches below particularly good / bad from an efficieny point of view?
-
Option 1: looping through an array of pre-canned masks, e.g. picking off particular bits
unsigned char mask[8]={0x80,0x40,0x20,0x10,0x8,0x4,0x2,0x1}; for(i=0;i<8;i++) { ... (mask[i] & mem_data ) ...}
-
Option 2: down-shifting more than one place on each loop iteration
unsigned char mask=0x80; for(i=0;i<8;i++) { ... mem_data & (mask>>i) ... } -
Option 3: down-shifting exactly one place on each loop iteration
unsigned char mask=0x80; while(mask) { ... mem_data & mask mask>>=1; ... }
Edit: Removed putchar() from the examples so it does not distract from the question
Bit masks are often used in the embedded world.
Not all processors can do a bitwise shift with a variable argument. For example, on MSP430 processors you can only bitshift one bit at a time. The implementation will resort to software to shift with a variable amount. In that case the option number 2 has to be avoided. More generally look at the assembly output of your program to compare the most efficient solution.