-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathn_bit_adder.py
More file actions
87 lines (68 loc) · 2.89 KB
/
n_bit_adder.py
File metadata and controls
87 lines (68 loc) · 2.89 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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
"""
Dynamic N-Bit Binary Adder Simulator
Scales automatically to handle any integer size using software logic gates.
"""
# --- 1. Fundamental Logic Gates ---
def AND_gate(a, b): return a & b
def OR_gate(a, b): return a | b
def XOR_gate(a, b): return a ^ b
# --- 2. Combinational Logic Circuits ---
def half_adder(a, b):
return XOR_gate(a, b), AND_gate(a, b)
def full_adder(a, b, carry_in):
sum1, carry1 = half_adder(a, b)
sum2, carry2 = half_adder(sum1, carry_in)
return sum2, OR_gate(carry1, carry2)
# --- 3. Dynamic N-Bit Ripple Carry Adder ---
def dynamic_ripple_carry(bin_list1, bin_list2):
"""Adds two binary lists of ANY equal length."""
length = len(bin_list1)
result = [0] * length
carry = 0
# Iterate backwards through the dynamic length
for i in range(length - 1, -1, -1):
result[i], carry = full_adder(bin_list1[i], bin_list2[i], carry)
return result, carry
# --- 4. Dynamic Data Transformation ---
def get_bit_width(num1, num2):
"""Calculates the minimum required bit-width (e.g., 4, 8, 16) for the numbers."""
max_num = max(num1, num2)
if max_num < 16: return 4
elif max_num < 256: return 8
elif max_num < 65536: return 16
else: return 32
def int_to_dynamic_binary(num, width):
"""Converts an integer to a binary list of a specific width."""
binary_str = format(num, f'0{width}b')
return [int(bit) for bit in binary_str]
def binary_to_int(binary_list):
"""Converts a binary list back to an integer."""
return int("".join(str(bit) for bit in binary_list), 2)
# --- 5. Interactive Application Loop ---
def main():
print("=== Interactive N-Bit Logic Simulator ===")
print("Type 'quit' at any time to exit.\n")
while True:
try:
val1 = input("Enter first positive integer: ")
if val1.lower() == 'quit': break
val2 = input("Enter second positive integer: ")
if val2.lower() == 'quit': break
num1, num2 = int(val1), int(val2)
# Determine dynamic width and convert
width = get_bit_width(num1, num2)
bin1 = int_to_dynamic_binary(num1, width)
bin2 = int_to_dynamic_binary(num2, width)
print(f"\n[Hardware configured for {width}-bit addition]")
print(f"Input A: {num1:5} -> {bin1}")
print(f"Input B: {num2:5} -> {bin2}")
# Process through logic gates
result_bin, overflow = dynamic_ripple_carry(bin1, bin2)
result_int = binary_to_int(result_bin)
print("-" * (25 + (width * 3)))
print(f"Result: {result_int:5} -> {result_bin}")
print(f"Overflow Carry: {overflow}\n")
except ValueError:
print("[!] Invalid input. Please enter whole numbers only.\n")
if __name__ == "__main__":
main()