Reputation:
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
Upvotes: 2
Views: 1137
Reputation: 12980
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.
Upvotes: 0
Reputation: 36092
this should work
int a = 1; // 0001
int b = 3; // 0011
int c = 11; // 1011
int d = 0;
d = a & b & c;
Upvotes: 1
Reputation: 347556
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
.
Upvotes: 3