Last active
August 29, 2015 14:04
-
-
Save igorw/52a046008b15b01e122b to your computer and use it in GitHub Desktop.
A binary full adder. Inspired by The Reasoned Schemer.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
function bit_xor($x, $y) { | |
return intval($x xor $y); | |
} | |
function bit_and($x, $y) { | |
return intval($x && $y); | |
} | |
// [result, carry-out] | |
function half_adder($x, $y) { | |
return [ | |
bit_xor($x, $y), | |
bit_and($x, $y), | |
]; | |
} | |
// [result, carry-out] | |
function full_adder($x, $y, $cin) { | |
list($w, $xy) = half_adder($x, $y); | |
list($result, $wz) = half_adder($w, $cin); | |
return [ | |
$result, | |
bit_xor($xy, $wz), | |
]; | |
} | |
// 4-bit full-adder | |
$xs = array_reverse([1, 0, 1, 0]); | |
$ys = array_reverse([1, 0, 0, 1]); | |
$carry = 0; | |
$sum = []; | |
foreach (range(0, 3) as $i) { | |
list($bit, $carry) = full_adder($xs[$i], $ys[$i], $carry); | |
$sum[] = $bit; | |
} | |
$sum[] = $carry; | |
echo json_encode(array_reverse($sum))."\n"; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment