Four bit adder: Difference between revisions

Added solution for Action!
(Added Fōrmulæ solution)
(Added solution for Action!)
Line 78:
tot[width] = tlast
assert(a + b == bus2int(tot), ‘totals don't match: #. + #. != #.’.format(a, b, String(tot)))</lang>
 
=={{header|Action!}}==
<lang Action!>DEFINE Bit="BYTE"
 
TYPE FourBit=[Bit b0,b1,b2,b3]
 
Bit FUNC Not(Bit a)
RETURN (1-a)
 
Bit FUNC MyXor(Bit a,b)
RETURN ((Not(a) AND b) OR (a AND Not(b)))
 
Bit FUNC HalfAdder(Bit a,b Bit POINTER c)
c^=a AND b
RETURN (MyXor(a,b))
 
Bit FUNC FullAdder(Bit a,b,c0 Bit POINTER c)
Bit s1,c1,s2,c2
 
s1=HalfAdder(a,c0,@c1)
s2=HalfAdder(b,s1,@c2)
c^=c1 OR c2
RETURN (s2)
 
PROC FourBitAdder(FourBit POINTER a,b,s Bit POINTER c)
Bit c1,c2,c3
 
s.b3=FullAdder(a.b3,b.b3,0,@c3)
s.b2=FullAdder(a.b2,b.b2,c3,@c2)
s.b1=FullAdder(a.b1,b.b1,c2,@c1)
s.b0=FullAdder(a.b0,b.b0,c1,c)
RETURN
 
PROC InitFourBit(BYTE a FourBit POINTER res)
res.b3=a&1 a==RSH 1
res.b2=a&1 a==RSH 1
res.b1=a&1 a==RSH 1
res.b0=a&1
RETURN
 
PROC PrintFourBit(FourBit POINTER a)
PrintB(a.b0) PrintB(a.b1)
PrintB(a.b2) PrintB(a.b3)
RETURN
 
PROC Main()
FourBit a,b,s
Bit c
BYTE i,v
 
FOR i=1 TO 20
DO
v=Rand(16) InitFourBit(v,a)
v=Rand(16) InitFourBit(v,b)
FourBitAdder(a,b,s,@c)
 
PrintFourBit(a) Print(" + ")
PrintFourBit(b) Print(" = ")
PrintFourBit(s) Print(" Carry=")
PrintBE(c)
OD
RETURN</lang>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Four_bit_adder.png Screenshot from Atari 8-bit computer]
<pre>
0100 + 0000 = 0100 Carry=0
1101 + 1011 = 1000 Carry=1
1011 + 0010 = 1101 Carry=0
1101 + 0111 = 0100 Carry=1
0100 + 0101 = 1001 Carry=0
0110 + 1011 = 0001 Carry=1
1110 + 0010 = 0000 Carry=1
0010 + 1110 = 0000 Carry=1
1110 + 1110 = 1100 Carry=1
1100 + 0111 = 0011 Carry=1
0100 + 0011 = 0111 Carry=0
1101 + 0101 = 0010 Carry=1
0001 + 0011 = 0100 Carry=0
1001 + 1000 = 0001 Carry=1
1111 + 1001 = 1000 Carry=1
0001 + 0011 = 0100 Carry=0
0001 + 0000 = 0001 Carry=0
1000 + 0011 = 1011 Carry=0
1110 + 1000 = 0110 Carry=1
0010 + 0100 = 0110 Carry=0
</pre>
 
=={{header|Ada}}==
Anonymous user