Can two Bit Fields be AND'ed or OR'ed

I am coming from a Unisys Algol environment, yes there are few of us left, and have an application that makes extensive use of MASKS for monitoring different states. These MASKS are combined using an AND or OR, somtimes 4 different MASKS are AND'ed to create a set of items to work on.A Bit field seems to provide the best method of replicating the bit access but I don't see use of an AND or OR operation to combine these into another BitField. In Algol I can AND or OR these words to another word. This word operation is much faster than stepping through each bit and comparing then to create the result.
Was there a question in there somewhere? heh

Anyway you can do that in C/C++ too. The AND operator is & and the OR is |. There's also ^ for XOR and ~ for compliment (XOR with all 1s)

And there's also &=, |=, ^= for assignment

1
2
3
a = 0x1F;
a &= 0x23; // a == 0x03
a |= 0x16; // a == 0x17 
And bitshift: ">>" "<<" are right-shift and left-shift respectively. Plus you can >>= and <<=, e.g.
1
2
3
short i = 510;
char lo = (char)(i << 8), hi = (char)(i & 0x0F);
/* hi contains the high byte, and lo contains the low byte */


Also you can do this, which I think is pretty neat:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#define OPTION_A 0
#define OPTION_B 2
#define OPTION_C 4

int accept_3_options(int options)
{
    if ((options & OPTION_A) == OPTION_A)
        printf("You chose option A\n");

    if ((options & OPTION_B) == OPTION_B)
        printf("You chose option B\n");

    if ((options & OPTION_C) == OPTION_C)
        printf("You chose option C\n");
}


There's no way to implement a logical XOR afaik, though.
Last edited on
XOR is ^

1
2
3
unsigned char x = 0x0A;
x ^= 0xFF;
cout << "0x" << hex << (unsigned)x;

0xF5
That's bitwise XOR, not logical XOR. What I mean is there's no if (a ^^ b).
Last edited on
Whoops! I misread.

Just cast each expression to boolean first: if ((bool)a ^ (bool)b)

;-)
Oh, thanks.
Topic archived. No new replies allowed.