• 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?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

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

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
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.

It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today

From novice to tech pro — start learning today.