Jason Novinger@programming.devM to Python@programming.dev · edit-22 years ago[Meme] Swapping integers in Pythonlemmy.worldimagemessage-square15fedilinkarrow-up139arrow-down13file-textcross-posted to: programmerhumor@lemmy.ml
arrow-up136arrow-down1image[Meme] Swapping integers in Pythonlemmy.worldJason Novinger@programming.devM to Python@programming.dev · edit-22 years agomessage-square15fedilinkfile-textcross-posted to: programmerhumor@lemmy.ml
minus-squareHammerheart@programming.devlinkfedilinkarrow-up1·2 years agoI’m gonna need you to elaborate on this one
minus-squaredmad@programming.devlinkfedilinkarrow-up5·edit-22 years agoxor has the property x ^ x = 0, and x ^ 0 = x. So, x ^ x ^ y = y a' = a ^ b b' = b ^ a' = b ^ (a ^ b) = a a'' = (a ^ b) ^ a = b This is pretty clever, I’ve never seen this for a swap.
minus-squareActuallyRuben@actuallyruben.nllinkfedilinkarrow-up2·2 years agoCouldn’t have explained it better myself. I don’t remember where exactly I first read about this trick, but it’s mainly useful in C or Assembly, as you don’t have to resort to using a third variable/register.
I’m gonna need you to elaborate on this one
xor has the property x ^ x = 0, and x ^ 0 = x. So, x ^ x ^ y = y
a' = a ^ b b' = b ^ a' = b ^ (a ^ b) = a a'' = (a ^ b) ^ a = b
This is pretty clever, I’ve never seen this for a swap.
Couldn’t have explained it better myself. I don’t remember where exactly I first read about this trick, but it’s mainly useful in C or Assembly, as you don’t have to resort to using a third variable/register.