And for another 'Best practice' query guaranteed to piss-off somebody...
Let's say you want to get the value of a group of bits from a byte that you've divided up into fields such as:
// DIP switch masks #define POLARITYMASK 0x01 // 00000001 #define SPEEDMASK 0x0E // 00001110 #define PATTERNMASK 0xF0 // 11110000
You can extract the pattern with:
pattern = ((dip_value & PATTERNMASK) >> 4 );
But suppose you want to write a generic function for your I-don't-want-to-think library that can do this sort of thing without you having to refer back to the mask to see where it is located so that you know how many shifts to use so you write:
uint8_t get_masked_field_8(uint8_t value, uint8_t mask) { uint8_t shift = 0; for(int i = 0; i < 8; i++) { if( ( (mask >> i) & 0x01 ) ) { shift = i; break; } } return( (value&mask) >> shift ); }
Then you can get the pattern by just calling:
pattern = get_mask_field(dip_value,PATTERNMASK);
And be done with it.
Is this a "˜best practice' algorithm for accomplishing this task or is their a better way?
Smiley