# Perl program to add two numbers using only bitwise operators # See https://stackoverflow.com/questions/4068033/add-two-integers-using-only-bitwise-operators use strict; use warnings; # See [id://11135535] (note that use integer subtly affects bit operations in Perl) use integer; sub BitAdd1 { my ($aa, $bb) = @_; my $carry = $aa & $bb; my $result = $aa ^ $bb; while ($carry != 0) { my $s_carry = $carry << 1; $carry = $result & $s_carry; $result ^= $s_carry; } return $result; } sub BitAdd2 { my ($aa, $bb) = @_; $bb == 0 and return $aa; return BitAdd2($aa ^ $bb, ($aa & $bb) << 1); } for my $r ( [0, 1], [1, -1], [69, -42], [42, 69], [-42, 69], [-42, -69], [256, 512], [123456789, 1], [2147483647, 1], [-2147483648, 1] ) { my $sum0 = $r->[0] + $r->[1]; my $sum1 = BitAdd1($r->[0], $r->[1]); my $sum2 = BitAdd2($r->[0], $r->[1]); print "$r->[0] + $r->[1] = $sum0 ($sum1 $sum2)\n"; $sum0 == $sum1 or die "oops 1"; $sum0 == $sum2 or die "oops 2"; $sum1 == $sum2 or die "oops 3"; }