Bite Bytes
Bite Bytes

Reputation: 1513

Bit manipulation and Flags testing in C

Suppose I have two variables of type int, a and b, and a flag F.

#define F <something>

int a = <something> ;
int b = <something> ;

What is a simple way to test that both a and b, have the flag F, or none of them has it?

To test if both of them have it, I can use something like:

if ( a & b & F )

To test if none of them has it, I can use something like:

if ( !((a & F) || (b & F)) )

And the whole test becomes:

if ( (a & b & F) &&  !((a & F) || (b & F)) )

But this looks, too long and too complicated. Is there any simpler solution?

Upvotes: 2

Views: 293

Answers (3)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726499

You are looking for bit equality, which can be tested by applying XOR operator ^, inverting the result, and masking.

a ^ b sets bits to 1 only where the corresponding bits of a and b are different. For corresponding bits that are the same the result bit will be set to zero.

If you invert the result, you'd get ones in positions of equal bits:

~(a ^ b)

The only thing that remains is to mask with F, and check for equality:

if ((~(a ^ b) & F) == F) {
    ... // All bits indicated by F are set to the same value in a and b
}

Upvotes: 2

0___________
0___________

Reputation: 67476

Maybe this one

!((a & F) ^ (b & F))

Upvotes: 2

MikeCAT
MikeCAT

Reputation: 75062

The test for "none of them has it" can be

!((a | b) & F)

Merge the flags, mask and flip the logic.


The whole test can be written using xor. (Thanks to Martin James for the idea)

!((a ^ b) & F)

This means "not (exactly one of a or b has F)"

Upvotes: 3

Related Questions