PassionateDeveloper
PassionateDeveloper

Reputation: 15138

Bitwise check if some flags are set, others aren't?

I have a int-flag which will be like this:

Now I have this code:

if (flag & 4) //Beantwortet
{
    imageView.image = [UIImage imageNamed:@"beantwortet-40.png"];
}
else  if (flag & 2) //ungelesen
{
    imageView.image = [UIImage imageNamed:@"Flag1-40.png"]; 
    
}
else
{
       imageView.image = [UIImage imageNamed:@"neu-40.png"];
}

Which means first if: answered, second if: readed, last if: unreaded.

Now a user can be answered a mail, but set the flag manually to unread. That means the int value is 5.

How to check this?

I tried this:

else if (flag & 4 && flag & 1) //Beantwortet, aber auf "Nicht gelesen" gesetzt
{
    imageView.image = [UIImage imageNamed:@"neu-40.png"];
}

But I not only get 5 in this, I get 7 also.
How to check for 5, but not for 7?

Upvotes: 2

Views: 248

Answers (2)

fbrereto
fbrereto

Reputation: 35925

Why not just check to see if the int value is 5, like you say?

else if (flag == 5) //Beantwortet, aber auf "Nicht gelesen" gesetzt
{
    imageView.image = [UIImage imageNamed:@"neu-40.png"];
}

Update : If you have more flags beyond the first four, you can pre-filter the value and then do the check:

else if ((flag & 7) == 5) //Beantwortet, aber auf "Nicht gelesen" gesetzt
{
    imageView.image = [UIImage imageNamed:@"neu-40.png"];
}

That will mask out all the flags except for the first three, so even if others are set at e.g., 8 or 16, they will not play a part in this check.

Upvotes: 1

matthias
matthias

Reputation: 2499

The obvious would be if((flag & 5) && !(flag & 2))

Upvotes: 1

Related Questions