Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 284
rsk82 Avatar asked Mar 08 '13 18:03

rsk82


2 Answers

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
like image 63
Lie Ryan Avatar answered Oct 18 '22 15:10

Lie Ryan


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.

like image 45
ted Avatar answered Oct 18 '22 14:10

ted