Checking multiple bits using bitwise operators

Posted on 2006-03-21
Last Modified: 2010-04-15
As a follow-up question to my previous question here,,

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.

Question by:chsalvia
    LVL 84

    Accepted Solution

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

    Expert Comment

    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.


    Featured Post

    IT, Stop Being Called Into Every Meeting

    Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

    Join & Write a Comment

    An Outlet in Cocoa is a persistent reference to a GUI control; it connects a property (a variable) to a control.  For example, it is common to create an Outlet for the text field GUI control and change the text that appears in this field via that Ou…
    This is a short and sweet, but (hopefully) to the point article. There seems to be some fundamental misunderstanding about the function prototype for the "main" function in C and C++, more specifically what type this function should return. I see so…
    Video by: Grant
    The goal of this video is to provide viewers with basic examples to understand and use nested-loops in the C programming language.
    Video by: Grant
    The goal of this video is to provide viewers with basic examples to understand and use while-loops in the C programming language.

    728 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    19 Experts available now in Live!

    Get 1:1 Help Now