|
发表于 2023-1-9 01:26:54
|
显示全部楼层
不能用 '+' 这个运算符,那就自己做一个加法器
- sh-5.1$ cat main.py
- #!/usr/bin/env python
- #coding=utf-8
- '''
- def and_gate(a, b):
- if a == 0: return 0
- if b == 0: return 0
- return 1
- def or_gate(a, b):
- if a == 1: return 1
- if b == 1: return 1
- return 0
- def not_gate(a):
- if a == 0: return 1
- return 0
- def xor_gate(a, b):
- if a == b: return 0
- return 1
- def xor_gate(a, b):
- w0 = not_gate(a)
- w1 = not_gate(b)
- w2 = and_gate(a, w1)
- w3 = and_gate(b, w0)
- return or_gate(w2, w3)
- '''
- def and_gate(a, b): return a & b
- def or_gate(a, b): return a | b
- def not_gate(a): return int(not a)
- def xor_gate(a, b): return a ^ b
- def half_adder_1(a, b):
- s = xor_gate(a, b)
- c = and_gate(a, b)
- return (c, s)
- def full_adder_1(a, b, c):
- w0, w1 = half_adder_1(a, b)
- w2, w3 = half_adder_1(w1, c)
- w4 = or_gate(w0, w2)
- return (w4, w3)
- def full_adder_2(a, b, c):
- w0, w1 = full_adder_1(a & 0x0001, b & 0x0001, c)
- w2, w3 = full_adder_1(a >> 1, b >> 1, w0)
- result = (w3 << 1) | w1
- return (w2, result)
- def full_adder_4(a, b, c):
- w0, w1 = full_adder_2(a & 0x0003, b & 0x0003, c)
- w2, w3 = full_adder_2(a >> 2, b >> 2, w0)
- result = (w3 << 2) | w1
- return (w2, result)
- def full_adder_8(a, b, c):
- w0, w1 = full_adder_4(a & 0x000f, b & 0x000f, c)
- w2, w3 = full_adder_4(a >> 4, b >> 4, w0)
- result = (w3 << 4) | w1
- return (w2, result)
- def full_adder_16(a, b, c):
- w0, w1 = full_adder_8(a & 0x00ff, b & 0x00ff, c)
- w2, w3 = full_adder_8(a >> 8, b >> 8, w0)
- result = (w3 << 8) | w1
- return (w2, result)
- def full_adder_32(a, b, c):
- w0, w1 = full_adder_16(a & 0xffff, b & 0xffff, c)
- w2, w3 = full_adder_16(a >> 16, b >> 16, w0)
- result = (w3 << 16) | w1
- return (w2, result)
- '''
- print(full_adder_32(12345, 7366896, 0), 12345 + 7366896)
- print(full_adder_32(12745, 7471895, 0), 12745 + 7471895)
- print(full_adder_32(82345, 7586894, 0), 82345 + 7586894)
- '''
- def add(a, b): return full_adder_32(a, b, 0)[1]
- a = 13748389521
- b = 1912349134
- print(add(a, b), a + b)
- a = 13741234521
- b = 1919087134
- print(add(a, b), a + b)
- a = 93741
- b = 291987634
- print(add(a, b), a + b)
- a = 13748389521
- b = 1912349134
- print(add(a, b) == a + b)
- a = 13741234521
- b = 1919087134
- print(add(a, b) == a + b)
- a = 93741
- b = 291987634
- print(add(a, b) == a + b)
- sh-5.1$ ./main.py
- 15660738655 15660738655
- 15660321655 15660321655
- 292081375 292081375
- True
- True
- True
- sh-5.1$
复制代码 |
|