3

I was reading through some C code written online and came across the following line:

if(!(array[index] ^ array[index - 1]))

The ^ operator is a bitwise XOR, so I read this line to say that it will return true if "The array value at index is not different to the value at the previous index." Simplified, I read this as "If the array value at the index is the same as the one at the previous index."

When I read it like that, it seems like an overcomplicated way to write:

if(array[index] == array[index - 1])

Are these expressions the same? If not, then why? If I'm not misreading it, the best explanation I have is that since this code is involved with interrupts on clock signals it needs to be quick. Maybe a bitwise operation is faster than whatever goes on behind-the-scenes with ==?

clb9355
  • 289
  • 4
  • 16

1 Answers1

0

Yes, basically they are the same thing.

Let's see here:

 a    b     (a) xnor (b)
___|_____|_______________|
 0 |  0  |       1
 0 |  1  |       0
 1 |  0  |       0 
 1 |  1  |       1

As you can see here, the xnor returns 1 only when a and b are equal.

This is one of the most preferred technique used in embedded C, especially when you have memory, or time constrains.

Since Arithmetic Logic Units (ALU), include a n-bit XNOR circuit (n: depending on your processors architecture); comparison with XNOR would processed in one instruction cycle.

[Someone who has more experience can correct me if I am wrong.]

Community
  • 1
  • 1
blablabla
  • 96
  • 10