Hacker News
new
|
past
|
comments
|
ask
|
show
|
jobs
|
submit
login
mcintyre1994
on Feb 13, 2017
|
parent
|
context
|
favorite
| on:
The Three Ways of XOR
Imagine you only had 4 bit numbers (range 0-15) and you tried to do swap 14, 15 (1110, 1111). You can do that with xor but not with the add method, because you can't store a + b without a wider variable.
jonsen
on Feb 13, 2017
[–]
15 + 15 gives 14
14 - 15 gives 15
mcintyre1994
on Feb 13, 2017
|
parent
[–]
The way I wrote this was rubbish, edited. I was trying to get at if you have 1110, 1111 then 1110 + 1111 will overflow, but you could xor them.
jonsen
on Feb 13, 2017
|
root
|
parent
[–]
1110 + 1111 = 1101 1101 - 1110 = 1111 1101 - 1111 = 1110
Overflow doesn't matter if you just want to swap.
Sacho
on Feb 13, 2017
|
root
|
parent
|
next
[–]
(Assuming two's complement arithmetic, as amelius pointed out - I don't know if all programming languages and platforms use it)
mcintyre1994
on Feb 13, 2017
|
root
|
parent
|
prev
[–]
That's a really smart observation I hadn't made, thanks for explaining!
Guidelines
|
FAQ
|
Lists
|
API
|
Security
|
Legal
|
Apply to YC
|
Contact
Search: