while(y != 0) { int carry = x & y; x = x ^ y; y = carry << 1; } 

Please explain how this cycle works.

Closed due to the fact that the question is not clear to the participants by default locale , MihailPw , Regent , aleksandr barakin , αλεχολυτ 10 Oct '17 at 16:59 .

Try to write more detailed questions. To get an answer, explain what exactly you see the problem, how to reproduce it, what you want to get as a result, etc. Give an example that clearly demonstrates the problem. If the question can be reformulated according to the rules set out in the certificate , edit it .

  • What exactly is incomprehensible in it? - default locale
  • @defaultlocale, the way a combination of such bitwise operations leads to a result similar to that after addition. - ߊߚߤߘ
  • one
    @Arhad in this case, it makes sense for the author to ask a question about the algorithm (Why is the cycle with bitwise AND and shift equivalent to addition? And is it equivalent?). Then the respondents will not need to write the value of the cycle and operators. Conversely, if the author does not understand what this or that language construct does, then it makes sense to ask a more specific question about it. - default locale
  • I apologize for the incorrectly formulated question ... the string x = x ^ y; - Andrey Popov

1 answer 1

the string x = x ^ y interest

^ - means an exclusive or (XOR) bit operation:

enter image description here

The remarkable thing about XOR is that dual application of XOR restores the primary result, i.e.

 X==(X^Y)^Y 
  • one
    Well, it's about xor himself. However, on the issue it seems that the author is interested in how he, in combination with another pair of operations, replaces arithmetic addition. Although, the questioner accepted this answer, so it’s strange how that ... - ߊߚߤߘ