Skip to content

Instantly share code, notes, and snippets.

@plvhx
Last active October 22, 2022 13:44
Show Gist options
  • Save plvhx/e1b0d16a045cda808192b29d0379038e to your computer and use it in GitHub Desktop.
Save plvhx/e1b0d16a045cda808192b29d0379038e to your computer and use it in GitHub Desktop.
full-adder implementation
# 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])))
@achjailani
Copy link

This is really amazing :)

@MQBR
Copy link

MQBR commented Jul 17, 2022

ngeri mazeee : v

@ch0c01dxyz
Copy link

muantapp mass \ :v /

@pararang
Copy link

cool ✨

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment