What does ^ mean in objective c ios? [duplicate]

2019-02-22 07:04发布

问题:

This question already has an answer here:

  • What does the ^ operator do to a BOOL? 8 answers

Sorry to ask such a simple question but these things are hard to Google.

I have code in iOS which is connected to toggle which is switching between Celsius and Fahrenheit and I don't know what ^ 1 means. self.celsius is Boolean

Thanks

self.celsius = self.celsius ^ 1;

回答1:

It's a C-language operator meaning "Bitwise Exclusive OR".

Wikipedia gives a good explanation:

XOR

A bitwise XOR takes two bit patterns of equal length and performs the logical exclusive OR operation on each pair of corresponding bits. The result in each position is 1 if only the first bit is 1 or only the second bit is 1, but will be 0 if both are 0 or both are 1. In this we perform the comparison of two bits, being 1 if the two bits are different, and 0 if they are the same. For example:

    0101 (decimal 5)
XOR 0011 (decimal 3)
  = 0110 (decimal 6)

The bitwise XOR may be used to invert selected bits in a register (also called toggle or flip). Any bit may be toggled by XORing it with 1. For example, given the bit pattern 0010 (decimal 2) the second and fourth bits may be toggled by a bitwise XOR with a bit pattern containing 1 in the second and fourth positions:

    0010 (decimal 2)
XOR 1010 (decimal 10)
  = 1000 (decimal 8)


回答2:

It's the bitwise XOR operator (see http://www.techotopia.com/index.php/Objective-C_Operators_and_Expressions#Bitwise_XOR).

What it's doing in this case is switching back and forth, because 0 ^ 1 is 1, and 1 ^ 1 is 0.



回答3:

It's an exclusive OR operation.