It is important to remember that xor is a bitwise operator, so x ^= y
affects the individual bits of x based on the bits in y.

Think of xor as a bitwise not-equal operator. The expression

a = x ^ y

Will set the bits of "a" to true if the corresponding bits of "x" and
"y" are not equal.

Thus the xor operator is a good way to toggle selected bits in a
value. If I want to toggle the 1, 4, and 8 bit in x, I can write x ^=
13.

A nice property of xor is that it is self-reversing:

a ^= b;  // Toggle the bits set in b
a ^= b;  // Reverse the operation

After those two operations, a has the same value it had before.

That doesn't seem useful, but imagine that you are writing an
application where you allow the user to select a region in an image by
clicking on one corner and then drawing a "rubber band box" which
follows the mouse to select the other corner. If you just draw a white
line, you obliterate the image, so you would need to copy the pixels
which are covered by the box. But if you xor the pixels by some value
to draw the box, and xor the pixels again with the same value you end
up with the original value of the pixel.

The same thing can be used to encrypt data. If you xor each byte by a
byte produced by a stream generator based on a secret key, the
recipient can repeat the process and get the original data back.

Don

On Jun 13, 9:18 pm, Navneet Gupta <navneetn...@gmail.com> wrote:
> Hello,
>
> I would really appreciate if someone can help me get an intuitive
> understanding of XOR over a range of numbers.
>
> I have seen it's usage is a couple of problems where duplicates are involved
> and though ultimately i can see how it is solving the problem, i still feel
> like checking the correctness of the solution whenever i come across such
> solutions.
>
> Also would be good if someone can throw some light on what other kinds of
> problems they have seen which are difficult(time complexity wise) but using
> XOR gives an elegant and time efficient solution.
>
> --Navneet

-- 
You received this message because you are subscribed to the Google Groups 
"Algorithm Geeks" group.
To post to this group, send email to algogeeks@googlegroups.com.
To unsubscribe from this group, send email to 
algogeeks+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/algogeeks?hl=en.

Reply via email to