[Meme] Swapping integers in Pythonlemmy.worldimagecross-posted to: bumba@boomer.casinoprogrammerhumor@lemmy.ml Jason Novinger ( @jnovinger@programming.dev ) M Python@programming.dev • edit-21 year ago message-square17fedilinkarrow-up137
arrow-up137image[Meme] Swapping integers in Pythonlemmy.world Jason Novinger ( @jnovinger@programming.dev ) M Python@programming.dev • edit-21 year ago message-square17fedilinkcross-posted to: bumba@boomer.casinoprogrammerhumor@lemmy.ml
minus-square dmad ( @dmad@programming.dev ) linkfedilink5•edit-21 year 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-square ActuallyRuben ( @ActuallyRuben@actuallyruben.nl ) linkfedilink2•1 year 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.
xor has the property x ^ x = 0, and x ^ 0 = x. So, x ^ x ^ y = y
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.