1

Say you have two integers, A and B.

int A = 0b0011;
int B = 0b1001;

How do I determine if a 0 in A goes to a 1 in B.

I don't care if a 1 in A goes to 0 in B, or if the bit stays the same, only if a 0 goes to a 1.

The output I would want here would be:

result = 0b1000
H.S.
  • 11,654
  • 2
  • 15
  • 32
Leo0221
  • 21
  • 3
  • 3
    You need to calculate bitwise `~A & B`. – DYZ Mar 12 '20 at 01:48
  • 1
    Note that you ought to be using unsigned types for your bitwise operations; see https://stackoverflow.com/questions/11644362/are-the-results-of-bitwise-operations-on-signed-integers-defined – Nate Eldredge Mar 12 '20 at 03:18

1 Answers1

2

A xor B

0011
1001
----
1010

Result & B

1010
1001
----
1000

Xor sets to 1 bits that are different in A and B. But you are only interested in cases where 0' in A is 1' in B. To turn off such bits, simply & with B.

Tony Tannous
  • 14,154
  • 10
  • 50
  • 86