Jump to content
SubSpace Forum Network

Recommended Posts

Posted

i can remember reading about this in one of my books, but can't remember for the life of me what the heck it actually does. i saw it used to swap variables without using a temporary variable

 

int a = 1, b = 0;

a ^= b ^= a ^= b;

 

this sets a to 0 and b to 1

 

obviously it is overloaded so the original would be a = a ^ b;

 

anyone know?

Posted

Well, it's a funky one blum.gif A very useful one, too, if you like doing weird and funky stuff (and math/crypto).

 

It's the one and only exclusive or.

 

source ^ modifier = result

1001 ^ 1001 = 0000

1001 ^ 0110 = 1111

1001 ^ 0101 = 1100

 

If a source or modifier bit is one (but not both), the resulting bit is one.

Posted

well out of the context of 0's and 1's, i use it to swap out characters in a string, it works, and i just don't see how it works. maybe explain in being used to swap out characters in a character array?

 

thanks for the help smile.gif

Posted

You mean how you can do the thing in the first post?

Well, it all comes down to the ones and zeroes, really :p

 

byte a = 133, b = 44;

a ^= b ^= a ^= b;

 

What this does is as follows:

 

Note: a + b does not mean a sum here. It means a sort of a mix.

 

First, a is a and b is b.

The first op (a ^= B) causes a to become a mix of a and b (a is now a + B)

The second op (b ^= a) causes b to become a! What it does is this: it takes a (which is a + B) and then removes itself (B) from that value. So a + b becomes just a.

And the last op (a ^= B) removes the a part (which is now in B) from a + b (which is in a) and a becomes only b.

Guest
This topic is now closed to further replies.
×
×
  • Create New...