• C

Checking multiple bits using bitwise operators

As a follow-up question to my previous question here, http://www.experts-exchange.com/Programming/Programming_Languages/C/Q_21782586.html,

I'm trying to figure out how to compare multiple bits to check for multiple boolean variables.

As an example, the isalnum function.

Suppose you have:

#define 0x0001 ALPHA
#define 0x0002 DIGIT
#define 0x0003 TRAIT3
#define 0x0004 TRAIT4

int charmap[256];
charmap['A'] = ALPHA;

Now how would you check if an element of charmap is either alpha or numeric?  I tried:

return (charmap['A'] & ALPHA | DIGIT)

But when I combine two traits using the | operator, I always get a greater than 0 value, even if I try it with two traits both of which are incorrect.

Who is Participating?
ozoConnect With a Mentor Commented:
charmap['A'] & (ALPHA | DIGIT)
Hi chsalvia,

As ozo quite succinctly points out, your problem is operator precedence. The expression you have used will evaluate as:

(charmap['A'] & ALPHA) | DIGIT

which is clearly not what you want. To stop this hapening, change the order of evaluation using brackets as ozo suggests.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.