user142019
user142019

Reputation:

Using a bitwise AND on more than two bits

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

Answers (4)

JustJeff
JustJeff

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

AndersK
AndersK

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

Brian R. Bondy
Brian R. Bondy

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

CB Bailey
CB Bailey

Reputation: 793027

What's wrong with just this.

d = a & b & c;

Upvotes: 17

Related Questions