in reply to Re: Re: Re: Swapping two values
in thread Swapping two values
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 :-)
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Re: Re: Re: Re: Swapping two values
by Anonymous Monk on Feb 16, 2003 at 03:30 UTC | |
|
Re: Re: Re: Re: Re: Swapping two values
by sauoq (Abbot) on Feb 16, 2003 at 00:34 UTC |