rsk82
rsk82

Reputation: 29377

how to zero every bit when in second operand is 1?

example:

1010111110110001
0101011100010010
================
1010100010100001

 |0 1
-|----
0|0 1
1|0 0

how to do this operation in c++ /c++11 ?

Upvotes: 5

Views: 209

Answers (4)

joshuanapoli
joshuanapoli

Reputation: 2509

You want a bitwise AND of the compliment of the second operand.

int fun(int x, int y)
{
    return x & ~y;
}

Upvotes: 4

Mark Wilkins
Mark Wilkins

Reputation: 41232

You should be able to do a bitwise AND with the bitwise negation:

result = val1 & ~val2;

Upvotes: 6

ted
ted

Reputation: 4975

simple:

result = op1 & ~op2;

this inverts the second operand bitwise (1 becomes 0 and vice versa). After this you use a bitwise and. This is often called using a bitmask.

Upvotes: 6

Lie Ryan
Lie Ryan

Reputation: 64827

You can do a bitwise NOT and then AND them: a & ~b

Given:

 a     = 1010111110110001
 b     = 0101011100010010

Then negating b gives:

~b     = 1010100011101101

and doing a & ~b:

 a     = 1010111110110001
~b     = 1010100011101101
-------------------------
a & ~b = 1010100010100001

Upvotes: 7

Related Questions