0

I know that ^ is the xor operator in Java. But I couldn't understand it in the following context.

int step = 0;
...
step ^=1;

Source: Google Code Jam 2014 (Participant's answer)

File Link : here

5gon12eder
  • 24,280
  • 5
  • 45
  • 92
nanospeck
  • 3,388
  • 3
  • 36
  • 45
  • 6
    step = step ^ 1 ? – Kick Buttowski Jan 13 '15 at 06:32
  • 4
    It's just like all the other += etc. It performs the operation assigning its value to step. – ChiefTwoPencils Jan 13 '15 at 06:33
  • 1
    Not sure what the question is; since you know what an xor is, why ask the question? What this will do, if this is what you ask, is always invert the least significant bit of `step`. – fge Jan 13 '15 at 06:34
  • 1
    Why the downvote/question? What is wrong in not knowing ^= an operator in assignment operator category? It's very clear from the question. @KickButtowski solved my confusion. Thanks. – nanospeck Jan 13 '15 at 07:11

5 Answers5

2

^ stands for XOR operator.

a ^= b is equivalent to a = a ^ b

Keen Sage
  • 1,899
  • 5
  • 26
  • 44
  • @Sashwat, thnx. Can u write me an example with real values to make it clearer please? – nanospeck Jan 13 '15 at 06:37
  • @nanospeck You make it sound like you know that it's the XOR operator but that you do not know what XOR does. Is this the case? – keyser Jan 13 '15 at 06:38
  • @nanospeck - Check this to get more details on XOR operator. http://stackoverflow.com/questions/1991380/what-does-the-operator-do-in-java. I think you already might know that XOR does the bitwise XOR between its two operands – Keen Sage Jan 13 '15 at 06:40
2

it goes under assignment operator category like

 += -= *= /= %= &= ^= |= <<= >>= >>>=

means

^= bitwise exclusive OR and assignment operator

step ^=1; as same as step = step ^ 1;

Kick Buttowski
  • 6,709
  • 13
  • 37
  • 58
1

step ^=1 means step = step xor 1. Similar to step += 1 which gets evaluated to step = step + 1

So ^= is short hand xor operator.

So xor table says:

operand1   operand2    output
   0          0         0
   0          1         1
   1          0         1
   1          1         0

so if my step is 1, then 1 xor 1 would be 0.

SMA
  • 36,381
  • 8
  • 49
  • 73
1

From Java Tutorials,

^ Assume integer variable A holds 60 and variable B holds 13 then: Binary XOR Operator copies the bit if it is set in one operand but not both.(A ^ B) will give 49 which is 0011 0001

In your case it is,

step = step^1

and in result you get step=1

http://www.tutorialspoint.com/java/java_basic_operators.htm

Afzal Ahmad
  • 586
  • 5
  • 20
1

As others have pointed out, step ^=1 flips the least significant bit of step. This makes even numbers get 1 bigger, and odd numbers get 1 smaller.

Examples:

 0 --> 1
 1 --> 0
 7 --> 6
 6 --> 7
-3 --> -4
Paul Boddington
  • 37,127
  • 10
  • 65
  • 116