Reputation: 13195
I would like to create a mask that sets the bits for the first n
nybbles,
and the first m
bits of these nybbles, where n <=8
and m <=4
.
By efficient, I mean a way that minimizes bitwise operations.
Currently I use a brute force approach: first create a nybble mask, then keep left shifting the mask and ORing these numbers together.
Here is my current method:
#define NIBBLE ((unsigned int)0xF >> m))
#define MASK ((NIBBLE | (NIBBLE << 4) | (NIBBLE << (8)) | (NIBBLE << (12)) | (NIBBLE << (16)) | (NIBBLE << (20)) | (NIBBLE << (24)) | (NIBBLE << (28))) >> (n*4) )
Upvotes: 0
Views: 1417
Reputation: 12609
/* Mask within nibble: 2**n - 1 */
int i;
unsigned int mask = 1;
for (i = 0; i < n; ++i) mask *= 2;
mask -= 1;
/* For all nibbles: multiply mask by 16 for each */
unsigned int nibblemask = 0;
for (i = 0; i < m; ++i) {
nibblemask += mask;
mask *= 16;
}
BTW, what's wrong with bitwise operations? They are more efficient. See Falk Hüffner's answer...
Upvotes: 1