Reputation: 43
I'm from a game programming background and I've just come across a bitwise XOR ^. I've seen examples of how it works with integers, but I'm a bit confused about the result with boolean values. I know a bool is either 0 or 1, but after testing I haven't been able to replicate the ^ result with simple operators. Could someone please explain to me what the following code snippet (specifically the ^) is doing? Many thanks.
bool body1awake = rigidbody1.isAwake;
bool body2awake = rigidbody2.isAwake;
if (body1awake ^ body2awake)
{
if (body1awake) rigidbody2.SetAwake();
else rigidbody1.SetAwake();
}
Upvotes: 2
Views: 909
Reputation: 234665
As bool
is a narrower type than an int
, both arguments are implicitly converted to an int
prior to the XOR being evaluated. true
assumes the value 1
, and false
assumes the value 0
.
If that result is non-zero then the if
body runs, and that happens if and only if body1awake
is not equal to body2awake
.
So perhaps the equivalent
if (body1awake != body2awake)
would have been better. If the author thinks their way is faster then they need a stern talking to with compiler optimisations and as-if rule being introduced into the conversation.
Upvotes: 2
Reputation: 180500
Exclusive or of two bits is true when only one of them is set. If both are set or not set then it is false. Since bool
basically represents a single bit (0 or 1 are its only values)
if (body1awake ^ body2awake)
means that the condition will be true on when body1awake != body2awake
.
Upvotes: 3