bit logical operators

Hello!

In my program I've to control input.I choose to set a integer variable (8 bit) to 0 and set, with bit OR operator, a specific bit in case the input are affected by one specific error.

For example:
1
2
3
4
5
6
7
8
9
10
11
12
...
#define ERROR1 4
#define ERROR2 8
...
result = 0; //00000000
if (first_error_affects_input() == true)
result |= ERROR1; // 00000100

if (second_error_affects_input() == true)
result |= ERROR2; // 00001000 or 00001100 depending on previous control

...


and so on. The functions in the conditions are example functions which check for a particular condition over the input (they aren't important now).

Now, I'd like to recognize the errors and create a concatenated string of the errors, so I can wanr the user with only one error message.

The question is: how can I isolate the set bits?
I'd not like to use bit right shift , so is there a way (for example using bit OR or AND logical operators) to recognize every single set bit?

Thanks
Last edited on
1
2
3
4
5
6
7
8
9
if(result & ERROR1)
{
  // ERROR1 bit was set
}
if(result & ERROR2)
{
  // ERROR2 bit was set
}
//... 


EDIT: but if you want a complete string with all the errors... I'd use a lookup table of sorts:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
const char* errorstrings[] = {
  "Erorr 1 occurred.",
  "Error 2 occurred.",
 //...
};

// see if there are any errors
if(result)
{
  string err = "You had the following errors:";
  for(int i = 0, i <= 8; ++i)
  {
    if(result & (1<<i))
    {
      err += "\n";
      err += errorstrings[i];
    }
  }
  cout << err;
}
Last edited on
Oh! So simple! :D
So, in this case, I use the fact that 0 is false and disequal from 0 is true...thanks :)
Disch's method works if none of the error flags set more than one bit at a time. Otherwise, the proper method would be ((result&ERROR1) == ERROR1) (the parentheses are important, as == has higher precedence).
thank you both :)
Topic archived. No new replies allowed.