Last active
October 22, 2022 13:44
-
-
Save plvhx/e1b0d16a045cda808192b29d0379038e to your computer and use it in GitHub Desktop.
full-adder implementation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Full adder implementation | |
# Paulus Gandung Prakosa <[email protected]> | |
# ref: https://en.wikipedia.org/wiki/Adder_(electronics)#Full_adder | |
import math | |
import sys | |
def bit_count(x): | |
return x if x == 0 else math.floor(math.log2(x)) + 1 | |
def extract_bit(x, pos): | |
if pos == 0: | |
return False | |
return (x & (1 << (pos - 1))) >> (pos - 1) | |
def _xor(a, b): | |
return a ^ b | |
def _and(a, b): | |
return a & b | |
def _or(a, b): | |
return a | b | |
def add(x, y): | |
a = bit_count(x) | |
b = bit_count(y) | |
p = (a if a > b else b) | |
r = c = 0 | |
for i in range(1, p + 1): | |
o = extract_bit(x, i) | |
l = extract_bit(y, i) | |
t = _xor(_xor(c, o), l) | |
c = _or(_and(o, l), _and(c, _xor(o, l))) | |
r = _or(r, (1 << (i - 1)) if t == 1 else 0) | |
if c == 1: | |
r = _or(r, 1 << p) | |
return r | |
if __name__ == '__main__': | |
print(add(int(sys.argv[1]), int(sys.argv[2]))) |
ngeri mazeee : v
muantapp mass \ :v /
cool ✨
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is really amazing :)