-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path2adder.js
More file actions
27 lines (22 loc) · 893 Bytes
/
Copy path2adder.js
File metadata and controls
27 lines (22 loc) · 893 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
// Two-bit binary adder (manual chaining of two full adders)
let a = [1, 1];
let b = [1, 1];
let carry = 0; // initial carry-in
let result = []; // will hold the sum bits
let sumLSB = a[1] ^ b[1] ^ carry; // sum = a xor b xor carry-in
let carryOut = (a[1] & b[1]) | (b[1] & carry) | (a[1] & carry); // carry-out
result[1] = sumLSB; // store LSB in result[1]
carry = carryOut; // propagate carry
let sumMSB = a[0] ^ b[0] ^ carry;
let carryOut2 = (a[0] & b[0]) | (b[0] & carry) | (a[0] & carry);
result[0] = sumMSB; // store MSB in result[0]
carry = carryOut2; // final carry after most significant bit
// If final carry is 1, we need an extra most significant bit
if (carry === 1) {
result.unshift(1);
}
// Display the result
console.log(' ', a);
console.log(' ', b);
console.log('------------');
console.log(result);