Jacko
Jacko

Reputation: 13195

Most efficient way of creating a 32 bit bitmask

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

Answers (2)

Falk H&#252;ffner
Falk H&#252;ffner

Reputation: 5040

You can use

(0x0f0f0f0f ^ (0xf0f0f0f0 >> m)) >> (4*n)

Upvotes: 5

SzG
SzG

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

Related Questions