PhpSnip.com

User Stats

Bitwise Arithmatic

This script does Addition and Subtraction without once using the + or - operators. Good example of how to use bitwise operators.

Info

 Download  View Source (print view)
 Rating : 4.7  Views : 157

Source Code ( 47 lines )

<?php
if (isset($num1) && isset($num2))
{

function BinaryAdd($num1,$num2)
{
  $carry = $num1 & $num2;
  do
  {
    $carry = $carry << 1;
    $num1  = $num1 ^ $num2;
    $sum   = $num1 ^ $carry;
    $num2  = $carry;
    $carry = $num1 & $num2;
  } while($carry != 0);
  return $sum;
}

function BinarySubtract($num1,$num2)
{
  //Compute Two's Compliment
  $num2 = ~ $num2;
  $num2 = BinaryAdd($num2,1);

  $diff = BinaryAdd($num1,$num2);
  return $diff;
  
}

  //Make sure form data is treated like an int   
  $number1 = (int)$num1;
  $number2 = (int)$num2;

  $sum = BinaryAdd($number1,$number2);
  $diff = BinarySubtract($number1,$number2);

  echo "The Sum is $sum<BR>";
  echo "The Difference is $diff";

} else {
?>
<Form Action="<? echo $PHP_SELF ?>" Method=Post>
Enter an Integer <Input Type=text name="num1"><BR>
Enter a Second Integer <Input Type=text name="num2"><BR>
<Input Type=Submit Value="Add and Subtract Them">
</Form>
<? } ?>

Search

Subscribe

  Rss Feeds

Sponsors

Advertise