Bitwise OR and AND

Started by
34 comments, last by peter86 21 years, 3 months ago
lol, I must have been typing
Advertisement
quote:Original post by Zipster
a ^= b
b ^= a
a ^= b


What does those lines do? Can you explain?
Well, that''s a fast way of switching the values of two variables.

I always like to put the logic of such statements into sentence form. Basically, after a ^= b, a is now basically a bit field which describes which bits were different between a and b (1 = different, 0 = same). When you do b ^= a, all the bits in b that were different between a and b get switched. Logically, it makes sense. If the bits were different, you switch them. So now b contains the original value of a. The last line, a ^= b, remember that a still describes what is different between a and b, and b now stores the original value of a. So now all the bits in a that are different from b get switched. Since b contains the original a, now a contains the original b.

Hope that made sense, heh
quote:Original post by Thunder_Hawk
As you can see, I figured that out just before you posted. The only reason I said that is b/c I remember another thread where someone kept using this as an arguement, and no one ever challenged the validity of the statement.


Actually, the statement was correct (unless he made some other error I don''t know about). The PROBLEM arises when the two variables are actually references to the same value. Let''s look at it again:

void swap(int &a, int &b){    a ^= b;    b ^= a;    a ^= b;} 


now call it as so:
int x = 7;swap(x, x); 


Whoops! That first ecks-or changes x to 0, and 0 it remains. THAT is the situation under which the xor swap does not work.

Don''t listen to me. I''ve had too much coffee.

a = b+a;
b = a-b;
a = a-b;
Arrg!!
(I think) That looks as a fast way to switch variables, but in fact isn''t. You have to load the two variable into processor registries to use XOR on them, then send them back to their original location, like this:

a->reg1
b->reg2
[3xXOR]
reg1->a
reg2->b

Why not simply do:

a->reg1
b->reg2
reg1->b
reg2->a

(I don''t know if b->a is legal).


ToohrVyk
-------------
Extatica - a free 3d game engine
Available soon!
Click here to learn more

This topic is closed to new replies.

Advertisement