# 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 :-) |