Skip to content

Instantly share code, notes, and snippets.

@igorw
Last active August 29, 2015 14:04
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save igorw/52a046008b15b01e122b to your computer and use it in GitHub Desktop.
Save igorw/52a046008b15b01e122b to your computer and use it in GitHub Desktop.
A binary full adder. Inspired by The Reasoned Schemer.
<?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