0

I am trying to write a simple C bitwise operation that returns YES if the bits are equal. Truth table is the following:

enter image description here

I tried various combinations of AND,XOR and OR and no luck. Granted, I could scan each bit pair and ask the question using an "IF" statement but rather do it more elegantly.

This is an example of what I need:

x = 251 - 11111011
y = 18  - 00010010
r = 22  - 00010110

1 Answers1

7

@daniel, @Barmar and @pignotto have given the answer in comments, but to make it clear for you. Make a truth table for the XOR operator (which in C would be X ^ Y):

X Y R
0 0 0
0 1 1
1 0 1
1 1 0

This is the inverse of what you want - i.e. where R is 0, you want 1 and vice-versa.

So you want R = ~(X ^ Y).

The ~ operator inverts all the bits, turning 0 into 1 and 1 into 0.

Equivalent expressions are ~X ^ Y and X ^ ~Y. If X or Y is a constant or is used repeatedly where it does not vary (as in a loop), then ~X or ~Y could be computed in advance, leaving only XOR to be computed. (This is a minor optimization, and a modern compiler might make it automatically.)

InSync
  • 4,851
  • 4
  • 8
  • 30
pmacfarlane
  • 3,057
  • 1
  • 7
  • 24
  • `~X ^ Y` has the same result and should be mentioned in case `X` is constant, so `~X` can be computed at compile time (or as a loop invariant etc.), thus saving one operation at run-time. Although the compiler might recognize this anyway as part of optimization. – Eric Postpischil Apr 28 '23 at 00:29
  • @EricPostpischil Please edit my answer to that effect if you wish. – pmacfarlane Apr 28 '23 at 00:31