views:

134

answers:

4

Hi, I am pretty new to bitwise operators. Let's say I have 3 variables a, b and c, with these values in binary:

  a = 0001
  b = 0011
  c = 1011

Now, I want to perform a bitwise AND like this:

    a
AND b
AND c
--------
d = 0001

d &= a &= b &= c doesn't work (as I expected), but how can I do this? Thanks

+16  A: 

What's wrong with just this.

d = a & b & c;
Charles Bailey
Oh damn ofcourse. I forgot I can use them without an `=`. Thanks!
Time Machine
+3  A: 

You want:

d = a & b & c;

&= means bitwise AND and also assign.

If d was originally assinged to be 0 your expression as you put it would always evaluate to 0 because anything & 0 will equal 0.

Brian R. Bondy
+1  A: 

this should work

int a = 1;  // 0001
int b = 3;  // 0011
int c = 11; // 1011
int d = 0;

d = a & b & c;
Anders K.
A: 

You probably just forgot to initialize 'd' to being all 1's, and it defaulted to 0. You can easily set all the bits to 1 by assigning d=-1, or if you prefer, d=0xffffffff, although since you were only using 4 bits, d=0xF would have sufficed.

That being said, daisy-chaining operators like that tends to be less readable than breaking things out as others have suggested.

JustJeff