|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Gates: XOR properties |
|
|
|
|
|
|
|
|
|
More XOR tricks (amaze
your friends!): |
|
|
|
Classic swap problem
(early CMSC 106) |
|
|
|
|
|
temp = x; |
|
|
|
|
|
x = y; |
|
|
|
|
|
|
y = temp; |
|
|
|
|
|
|
|
|
Using XOR: |
|
|
|
|
|
x = x ^ y ; |
|
|
|
|
|
y = x ^ y ; |
|
|
|
|
|
|
x = x ^ y ; |
|
|
|
|
Let x0 be the original value of x, y0 be the original value of y: |
|
|
|
|
|
x = x ^ y = x0 ^ y0 |
|
|
|
|
|
y = x ^ y = (x0 ^ y0) ^ y0 |
Substitute for x |
|
|
|
|
|
= x0 ^
(y0 ^ y0) |
|
Associative property |
|
|
|
|
|
= x0 ^ 0 |
|
|
x ^ x = 0 |
|
|
|
|
|
= x0 |
|
|
Identity |
|
|
|
|
x = x ^ y = (x0 ^ y0) ^ x0 |
Substitute for x and y |
|
|
|
|
|
= (x0 ^ x0) ^ y0 |
|
Associative, symmetric
properties |
|
|
|
= 0 ^ y0 |
|
x ^ x = 0 |
|
|
|
|
|
= y0 |
|
|
Identity |
|
|
|
|
What other operator is a
less-safe way of doing this? |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|