2019-05-05_full-adder-code.html


001| #:name::Full Adder Code
002| #:link::https://thehardcorecoder.com/2019/05/05/full-adder-code/
003| #:date::2019-05-05
004| #:code::
005| def full_adder_1 (a, b, ci):
006|     '''Full Adder Implementation #1.'''
007| 
008|     # Full adder logic table...
009|     logic_table = [
010|         [[[0,0],[1,0]], [[1,0],[0,1]]], # a=0
011|         [[[1,0],[0,1]], [[0,1],[1,1]]], # a=1
012|     ] # b=0 b=1 b=0 b=1
013| 
014|     # Just lookup the answer...
015|     return logic_table[a][b][ci]
016| 
017| #:code::
018| def full_adder_2 (a, b, ci):
019|     '''Full Adder Implementation #2.'''
020| 
021|     # The logic of full adding...
022|     s = (a ^ b) ^ ci
023|     co = ((a ^ b) and ci) or (a and b)
024| 
025|     # Return the logic calculation...
026|     return (s,co)
027| 
028| #:code::
029| def full_adder_3 (a, b, ci):
030|     '''Full Adder Implementation #3.'''
031| 
032|     # The math of full adding...
033|     s = a + b + ci
034|     if s < 2: return (s, 0)
035| 
036|     # Constrain and return answer...
037|     return (s % 2, 1)
038| 
039| #:code::
040| def full_adder_4 (a, b, ci):
041|     '''Full Adder Implementation #4.'''
042| 
043|     # Manipulate full adder bits...
044|     s,co = (a+b, 0)
045|     if s == 2: s,co = (0, 1)
046|     s += ci
047|     if s == 2: s,co = (0, 1)
048| 
049|     # Return answer...
050|     return (s, co)
051| 
052| #:code::
053| def full_adder_5 (a, b, ci):
054|     '''Full Adder Implementation #5.'''
055| 
056|     # FSM state table...
057|     state_table = {
058|         'start':{0:'S#0', 1:'S#1'},
059|         'S#0':{0:'S#00', 1:'S#01'},
060|         'S#1':{0:'S#10', 1:'S#11'},
061|         'S#00':{0:'S#000', 1:'S#001'},
062|         'S#01':{0:'S#010', 1:'S#011'},
063|         'S#10':{0:'S#100', 1:'S#101'},
064|         'S#11':{0:'S#110', 1:'S#111'},
065|         'S#000':(0,0), 'S#001':(1,0), # final
066|         'S#010':(1,0), 'S#011':(0,1), # states
067|         'S#100':(1,0), 'S#101':(0,1), # "
068|         'S#110':(0,1), 'S#111':(1,1), # "
069|     }
070| 
071|     # Trace states based on inputs...
072|     state = state_table['start'][a]
073|     state = state_table[state][b]
074|     state = state_table[state][ci]
075| 
076|     # Return answer from final state...
077|     return state_table[state]
078| 
079| #:end:code::
080|