-
-
Notifications
You must be signed in to change notification settings - Fork 50.4k
Expand file tree
/
Copy pathfull_adder.py
More file actions
67 lines (53 loc) · 1.63 KB
/
full_adder.py
File metadata and controls
67 lines (53 loc) · 1.63 KB
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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
"""
A Full Adder is a fundamental combinational circuit in digital logic.
It computes the sum and carry outputs for two input bits and an input carry bit.
Truth Table:
-----------------------------------------
| A | B | Cin | Sum | Cout |
-----------------------------------------
| 0 | 0 | 0 | 0 | 0 |
| 0 | 1 | 0 | 1 | 0 |
| 1 | 0 | 0 | 1 | 0 |
| 1 | 1 | 0 | 0 | 1 |
| 0 | 0 | 1 | 1 | 0 |
| 0 | 1 | 1 | 0 | 1 |
| 1 | 0 | 1 | 0 | 1 |
| 1 | 1 | 1 | 1 | 1 |
-----------------------------------------
Refer:
https://en.wikipedia.org/wiki/Adder_(electronics)#Full_adder
"""
def full_adder(a: int, b: int, cin: int) -> tuple[int, int]:
"""
Compute the sum and carry-out for a Full Adder.
Args:
a: First input bit (0 or 1).
b: Second input bit (0 or 1).
cin: Carry-in bit (0 or 1).
Returns:
A tuple `(sum_bit, carry_out)`.
>>> full_adder(0, 0, 0)
(0, 0)
>>> full_adder(0, 1, 0)
(1, 0)
>>> full_adder(1, 0, 0)
(1, 0)
>>> full_adder(1, 1, 0)
(0, 1)
>>> full_adder(0, 0, 1)
(1, 0)
>>> full_adder(1, 1, 1)
(1, 1)
Raises:
ValueError: If any input is not 0 or 1.
"""
if a not in (0, 1) or b not in (0, 1) or cin not in (0, 1):
raise ValueError("Inputs must be 0 or 1.")
# Sum is XOR of the inputs
sum_bit = a ^ b ^ cin
# Carry-out is true if any two or more inputs are 1
carry_out = (a & b) | (b & cin) | (a & cin)
return sum_bit, carry_out
if __name__ == "__main__":
import doctest
doctest.testmod()