I think that the point the Anonymous Monk was making that it falls over badly if $a and $b refer to the same sequence of bits in memory. Consider:
# swap ($s, $p1, $p2, $n); # in $s swap the $n bits at bit $p1 and $p2 sub swap { vec($_[0],$_[1],$_[3]) ^= vec($_[0],$_[2],$_[3]); vec($_[0],$_[2],$_[3]) = vec($_[0],$_[1],$_[3]) ^ vec($_[0],$_[2], +$_[3]); vec($_[0],$_[1],$_[3]) = vec($_[0],$_[1],$_[3]) ^ vec($_[0],$_[2], +$_[3]); }; # swap first two and second two chars my $string = "ABCD"; print "$string\n"; swap($string, 0,16,16); print "$string\n";
The problem with code like this is that it falls down badly if the bits sequences being swapped overlap. Consider:
# swap first character with itself swap($string, 0, 0, 8);
Anything XORed with itself is zero. Oops :-)
In reply to Re^4: Swapping two values
by adrianh
in thread Swapping two values
by stu96art
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |