Kevin Nowalski

Web Developer

Binary Computation through PHP


In one of my recent interview coding questions, I was asked to write a function that would add two numbers but without arithmetic expressions. I thought to myself, how exactly would you be able to do that? What could they be referring to? After numerous Google searches I stumbled upon someone mentioning 2’s complement. Binary computation is how computers really add numbers, at the lowest levels. Machine language. I spent most of my weekend trying to figure this code out. I had to refresh my memory on how to calculate 2’s complement. It’s actually pretty simple once you get the basics down. Putting it in code is another thing. Anyways, check out my code below….

  // Set test cases to true
$n = true;
// Open file
$file = fopen("data.txt","r");
echo "Results: 
"; while ($line = fgets($file)) // Loop through input { sscanf($line, "%d %d", $par1, $par2); // Parse 2 integers if($n==true){ // Number of test cases $cases=$par1+1; //Test case n+1 $n = false; } else { $result = add($par1, $par2); // Add integers echo $result . "
"; $cases--; if($cases<=0) { exit; // Exit loop if last test case completed. } } } function add($xi, $yi){ //Add function / Bitwise arithmetic while($yi!=0){ $carry = $xi & $yi; $xi=$xi^$yi; $yi=$carry << 1; } return $xi; }

Some Data:

1 1
1 2

Here’s the link too: Bitwise.php