Four bit adder: Difference between revisions
m
syntax highlighting fixup automation
m (→{{header|UNIX Shell}}: FIx spelling of "adder.") |
Thundergnat (talk | contribs) m (syntax highlighting fixup automation) |
||
Line 43:
{{trans|Python}}
<
R (a & !b) | (b & !a)
Line 77:
tot[i] = ta[i]
tot[width] = tlast
assert(a + b == bus2int(tot), ‘totals don't match: #. + #. != #.’.format(a, b, String(tot)))</
=={{header|Action!}}==
<
TYPE FourBit=[Bit b0,b1,b2,b3]
Line 141:
PrintBE(c)
OD
RETURN</
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Four_bit_adder.png Screenshot from Atari 8-bit computer]
Line 168:
=={{header|Ada}}==
<syntaxhighlight lang="ada">
type Four_Bits is array (1..4) of Boolean;
Line 192:
Full_Adder (A (1), B (1), C (1), Carry);
end Four_Bits_Adder;
</syntaxhighlight>
A test program with the above definitions
<syntaxhighlight lang="ada">
with Ada.Text_IO; use Ada.Text_IO;
Line 247:
end loop;
end Test_4_Bit_Adder;
</syntaxhighlight>
{{out}}
<div style="height: 320px;overflow:scroll">
Line 513:
{{works with|Dyalog APL}}
{{works with|GNU APL}}
<
not ← { ~ ⍵ } ⍝ in Dyalog these assignments can be simplified to "not ← ~", "and ← ∧", etc.
and ← { ⍺ ∧ ⍵ }
Line 553:
⍝ And go
{ (randbits 4) demo randbits 4 ⊣ ⍵ } ¨ ⍳20
</syntaxhighlight>
{{Out}}
Line 580:
=={{header|AutoHotkey}}==
{{works with|AutoHotkey 1.1}}
<
B := 9
N := FourBitAdd(A, B)
Line 621:
Res := Mod(N, 2) Res, N := N >> 1
return, Res
}</
{{out}}
<pre>13 + 9:
Line 628:
=={{header|AutoIt}}==
===Functions===
<syntaxhighlight lang="autoit">
Func _NOT($_A)
Return (Not $_A) *1
Line 669:
Return $Q4 & $Q3 & $Q2 & $Q1
EndFunc ;==>_4BitAdder
</syntaxhighlight>
===Example===
<syntaxhighlight lang="autoit">
Local $CarryOut, $sResult
$sResult = _4BitAdder(0, 0, 1, 1, 0, 1, 1, 1, 0, $CarryOut) ; adds 3 + 7
Line 678:
$sResult = _4BitAdder(1, 0, 1, 1, 1, 0, 0, 0, 0, $CarryOut) ; adds 11 + 8
ConsoleWrite('result: ' & $sResult & ' ==> carry out: ' & $CarryOut & @LF)
</syntaxhighlight>
{{out}}
<pre>
Line 690:
==={{header|Applesoft BASIC}}===
<
110 S$ = "1100 + 1101 = " : GOSUB 400
120 S$ = "1100 + 1110 = " : GOSUB 400
Line 749:
910 D = B AND NOT A
920 C = C OR D
930 RETURN</
==={{header|BBC BASIC}}===
{{works with|BBC BASIC for Windows}}
<
PRINT "1100 + 1100 = ";
PROC4bitadd(1,1,0,0, 1,1,0,0, e,d,c,b,a) : PRINT e,d,c,b,a
Line 797:
c& = a& AND NOT b&
d& = b& AND NOT a&
= c& OR d&</
{{out}}
<pre>
Line 811:
=={{header|Batch File}}==
<
@echo off
setlocal enabledelayedexpansion
Line 948:
if %1==1 if %2==1 exit /b 1
exit /b 0
</syntaxhighlight>
{{out}}
<pre>
Line 957:
=={{header|C}}==
<
typedef char pin_t;
Line 1,026:
return 0;
}</
=={{header|C sharp|C#}}==
{{works with|C sharp|C#|3+}}
<
using System;
using System.Collections.Generic;
Line 1,160:
}
</syntaxhighlight>
=={{header|C++}}==
Line 1,166:
=={{header|Clojure}}==
<
(ns rosettacode.adder
(:use clojure.test))
Line 1,201:
(n-bit-adder [true true true true true true] [true true true true true true])
=> (false true true true true true true)
</syntaxhighlight>
===Second Clojure solution===
<
;; a bit is represented as a boolean (true/false)
Line 1,256:
)
</syntaxhighlight>
===Using Bitwise Operators===
<
(defn to-binary-seq [^long x]
(map #(- (int %) (int \0))
Line 1,293:
(is (= (Long/parseLong (apply str (ripple-carry-adder (to-binary-seq 130) (to-binary-seq 250))) 2)
(+ 130 250))))
</syntaxhighlight>
=={{header|COBOL}}==
<syntaxhighlight lang="cobol">
program-id. test-add.
environment division.
Line 1,405:
end program add-4b.
</syntaxhighlight>
{{out}}
<pre>
Line 1,420:
This code models gates as functions. The connection of gates is done via custom logic, which doesn't involve any cheating, but a really good solution would be more constructive, i.e. it would show more of a notion of "connecting" up gates, using some kind of graph data structure.
<
# ATOMIC GATES
not_gate = (bit) ->
Line 1,460:
adder = n_bit_adder(4)
console.log adder [1, 0, 1, 0], [0, 1, 1, 0]
</syntaxhighlight>
=={{header|Common Lisp}}==
<
(defun half-adder (a b)
(list (logxor a b) (logand a b)))
Line 1,495:
(main)
</syntaxhighlight>
output:
<pre>
Line 1,508:
=={{header|D}}==
From the C version. An example of SWAR (SIMD Within A Register) code, that performs 32 (or 64) 4-bit adds in parallel.
<
void fourBitsAdder(T)(in T a0, in T a1, in T a2, in T a3,
Line 1,574:
writefln(" s0 %032b", s0);
writefln("overflow %032b", overflow);
}</
{{out}}
<pre> a3 00000000000000000000000000000000
Line 1,592:
overflow 11111111111111111111111111111111</pre>
128 4-bit adds in parallel:
<
void fourBitsAdder(T)(in T a0, in T a1, in T a2, in T a3,
Line 1,657:
writefln(" s0 %(%08b%)", s0.array);
writefln("overflow %(%08b%)", overflow.array);
}</
{{out}}
<pre> a3 00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
Line 1,675:
overflow 11111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111</pre>
Compiled by the ldc2 compiler to (where T = ubyte32, 256 adds using AVX2):
<
pushl %ebp
movl %esp, %ebp
Line 1,713:
popl %ebp
vzeroupper
ret $160</
=={{header|Delphi}}==
{{libheader| System.SysUtils}}
{{Trans|C#}}
<syntaxhighlight lang="delphi">
program Four_bit_adder;
Line 1,896:
Readln;
end.
</syntaxhighlight>
{{out}}
<pre>
Line 2,159:
{{works with|Elixir|1.1}}
{{trans|Ruby}}
<
use Bitwise
@bit_size 4
Line 2,205:
end
RC.task</
{{out}}
Line 2,231:
=={{header|Erlang}}==
Yes, it is misleading to have a "choose your own number of bits" adder in the four_bit_adder module. But it does make it easier to find the module from the Rosettacode task name.
<syntaxhighlight lang="erlang">
-module( four_bit_adder ).
Line 2,302:
%% xor exists, this is another implementation.
z_xor( A, B ) -> (A band (2+bnot B)) bor ((2+bnot A) band B).
</syntaxhighlight>
{{out}}
<pre>
Line 2,310:
=={{header|F_Sharp|F#}}==
<
type Bit =
| Zero
Line 2,347:
printfn "0001 + 0111 ="
b4A (Zero, Zero, Zero, One) (Zero, One, One, One) |> printfn "%A"
</syntaxhighlight>
{{out}}
<pre>
Line 2,355:
=={{header|Forth}}==
<
: "XOR" over over "NOT" and >r swap "NOT" and r> or ;
: halfadder over over and >r "XOR" r> ;
Line 2,366:
;
: .add4 4bitadder 0 .r 4 0 do i 3 - abs roll 0 .r loop cr ;</
{{out}}
<pre>1 1 0 0 0 0 1 1 .add4 01111
Line 2,373:
=={{header|Fortran}}==
{{works with|Fortran|90 and later}}
<
implicit none
Line 2,449:
end do
end do
end program</
{{out}} (selected)
<pre>1100 + 1100 = 11000
Line 2,469:
=={{header|FreeBASIC}}==
<
byref s as ubyte, byref c as ubyte)
s = a xor b
Line 2,506:
print "1111 + 1111 = ";
fourbit_add( 1, 1, 1, 1, 1, 1, 1, 1, s3, s2, s1, s0, carry )
print carry;s3;s2;s1;s0</
{{out}}<pre>
1100 + 0011 = 01111
Line 2,517:
Go does not have a bit type, so byte is used.
This is the straightforward solution using bytes and functions.
<
import "fmt"
Line 2,547:
// add 10+9 result should be 1 0 0 1 1
fmt.Println(add4(1, 0, 1, 0, 1, 0, 0, 1))
}</
{{out}}
<pre>
Line 2,555:
===Channels===
Alternative solution is a little more like a simulation.
<
import "fmt"
Line 2,680:
B[<-r4], B[<-r3], B[<-r2], B[<-r1], B[<-carry])
}
</syntaxhighlight>
Mini reference:
Line 2,689:
=={{header|Groovy}}==
<
static void main(args) {
Line 2,915:
adder4.setBit2 input
}
}</
=={{header|Haskell}}==
Basic gates:
<
import Data.List (mapAccumR)
Line 2,926:
band = min
bnot :: Int -> Int
bnot = (1-)</
Gates built with basic ones:
<
nand = (bnot.).band
xor a b = uncurry nand. (nand a &&& nand b) $ nand a b</
Adder circuits:
<
fullAdder (c, a, b) = (\(cy,s) -> first (bor cy) $ halfAdder (b, s)) $ halfAdder (c, a)
adder4 as = mapAccumR (\cy (f,a,b) -> f (cy,a,b)) 0 . zip3 (replicate 4 fullAdder) as</
Example using adder4
<
(1,[1,0,0,1])</
=={{header|Icon}} and {{header|Unicon}}==
Line 2,945:
Based on the algorithms shown in the Fortran entry, but Unicon does not allow pass by reference for immutable types, so a small <code>carry</code> record is used instead.
<
# 4bitadder.icn, emulate a 4 bit adder. Using only and, or, not
#
Line 3,047:
# cr.c is the overflow carry
return s
end</
{{out}}
Line 3,075:
===Implementation===
<
or=: +.
not=: -.
xor=: (and not) or (and not)~
hadd=: and ,"0 xor
add=: ((({.,0:)@[ or {:@[ hadd {.@]), }.@])/@hadd</
===Example use===
<
1 0 1 1 0</
To produce all results:
<
This will produce a 16 by 16 by 5 array, the first axis being the left argument (representing values 0..15), the second axis the right argument and the final axis being the bit indices (carry, 8, 4, 2, 1). In other words, the result is something like:
<
00000 00001 00010 00011 00100 00101 00110 00111 01000 01001 01010 01011 01100 01101 01110 01111
00001 00010 00011 00100 00101 00110 00111 01000 01001 01010 01011 01100 01101 01110 01111 10000
Line 3,107:
01101 01110 01111 10000 10001 10010 10011 10100 10101 10110 10111 11000 11001 11010 11011 11100
01110 01111 10000 10001 10010 10011 10100 10101 10110 10111 11000 11001 11010 11011 11100 11101
01111 10000 10001 10010 10011 10100 10101 10110 10111 11000 11001 11010 11011 11100 11101 11110</
Alternatively, the fact that add was designed to operate on lists of bits could have been incorporated into its definition:
<
Then to get all results you could use:
<
Compare this to a regular addition table:
<syntaxhighlight lang
(this produces a 10 by 10 array -- the results have no further internal array structure, though of course in the machine implementation integers can be thought of as being represented as fixed width lists of bits.)
Line 3,157:
=={{header|Java}}==
<
{
// Basic gate interfaces
Line 3,303:
}
}</
{{out}}
Line 3,320:
0s and 1s. To enforce this, we'll first create a couple of helper functions.
<syntaxhighlight lang="javascript">
function acceptedBinFormat(bin) {
if (bin == 1 || bin === 0 || bin === '0')
Line 3,335:
return true;
}
</syntaxhighlight>
===Implementation===
Line 3,342:
and, finally, the four bit adder.
<syntaxhighlight lang="javascript">
// basic building blocks allowed by the rules are ~, &, and |, we'll fake these
// in a way that makes what they do (at least when you use them) more obvious
Line 3,415:
return out.join('');
}
</syntaxhighlight>
===Example Use===
<
all results:
<syntaxhighlight lang="javascript">
// run this in your browsers console
var outer = inner = 16, a, b;
Line 3,433:
inner = outer;
}
</syntaxhighlight>
=={{header|jq}}==
Line 3,440:
All the operations except fourBitAdder(a,b) assume the inputs are presented as 0 or 1 (i.e. integers).
<
# These allow us to construct 'nand', 'or', and 'xor',
# and so on.
Line 3,481:
| fullAdder($inA[0]; $inB[0]; $pass.carry) as $pass
| .[0] = $pass.sum
| map(tostring) | join("") ;</
'''Example:'''
<
{{out}}
$ jq -n -f Four_bit_adder.jq
Line 3,490:
=={{header|Jsish}}==
Based on Javascript entry.
<
/* 4 bit adder simulation, in Jsish */
function not(a) { return a == 1 ? 0 : 1; }
Line 3,570:
PASS!: err = bad bit at a[3] of "2"
=!EXPECTEND!=
*/</
{{out}}
<pre>prompt$ jsish --U fourBitAdder.jsi
Line 3,594:
'''Functions'''
<
xor{T<:Bool}(a::T, b::T) = (a&~b)|(~a&b)
Line 3,624:
Base.bits(n::BitArray{1}) = join(reverse(int(n)), "")
</syntaxhighlight>
'''Main'''
<syntaxhighlight lang="julia">
xavail = trues(15,15)
xcnt = 0
Line 3,646:
bits(s), oflow))
end
</syntaxhighlight>
{{out}}
Line 3,664:
=={{header|Kotlin}}==
<
val Boolean.I get() = if (this) 1 else 0
Line 3,715:
for (j in i..minOf(i + 1, 15)) test(i, j)
}
}</
{{out}}
Line 3,771:
=={{header|Lambdatalk}}==
<syntaxhighlight lang="scheme">
{def xor
{lambda {:a :b}
Line 3,862:
14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
</syntaxhighlight>
=={{header|Lua}}==
<
function xor (a, b) return (a and not b) or (b and not a) end
Line 3,921:
print(add(0101, 1010)) -- 5 + 10 = 15
print(add(0000, 1111)) -- 0 + 15 = 15
print(add(0001, 1111)) -- 1 + 15 = 16 (causes overflow)</
Output:
<pre>SUM OVERFLOW
Line 3,931:
=={{header|M2000 Interpreter}}==
<syntaxhighlight lang="m2000 interpreter">
Module FourBitAdder {
Flush
Line 3,991:
}
FourBitAdder
</syntaxhighlight>
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<syntaxhighlight lang="text">and[a_, b_] := Max[a, b];
or[a_, b_] := Min[a, b];
not[a_] := 1 - a;
Line 4,009:
{s2, c2} = fulladder[a2, b2, c1];
{s3, c3} = fulladder[a3, b3, c2];
{{s3, s2, s1, s0}, c3}];</
Example:
<syntaxhighlight lang="text">fourbitadder[{1, 0, 1, 0}, {1, 1, 1, 1}]</
Output:
<pre>{{1, 0, 0, 1}, 1}</pre>
Line 4,018:
The four bit adder presented can work on matricies of 1's and 0's, which are stored as characters, doubles, or booleans. MATLAB has functions to convert decimal numbers to binary, but these functions convert a decimal number not to binary but a string data type of 1's and 0's. So, this four bit adder is written to be compatible with MATLAB's representation of binary. Also, because this is MATLAB, and you might want to add arrays of 4-bit binary numbers together, this implementation will add two column vectors of 4-bit binary numbers together.
<
%Make sure that only 4-Bit numbers are being added. This assumes that
Line 4,081:
v = num2str(v);
end
end %fourBitAdder</
Sample Usage:
<
S =
Line 4,137:
11
12</
=={{header|MUMPS}}==
<
QUIT (Y&'Z)!('Y&Z)
HALF(W,X)
Line 4,153:
FOR I=4:-1:1 SET T=$$FULL($E(Y,I),$E(Z,I),C4),$E(S,I)=$P(T,"^",1),C4=$P(T,"^",2)
K I,T
QUIT S_"^"_C4</
Usage:<pre>USER>S N1="0110",N2="0010",C=0,T=$$FOUR^ADDER(N1,N2,C)
Line 4,170:
The test code simulates the adder and exports trace wave file for debug support. Verilog and VHDL files are exported for hardware synthesis.
<
To run:
python3 Four_bit_adder_011.py
Line 4,311:
if __name__ == '__main__':
main()
</syntaxhighlight>
=={{header|Nim}}==
{{trans|Python}}
<
Bools[N: static int] = array[N, bool]
Line 4,348:
for a in 0..7:
for b in 0..7:
assert a + b == bus2int fa4(int2bus(a), int2bus(b))</
=={{header|OCaml}}==
<
(* File blocks.ml
Line 4,554:
(eval add4_io 4 4 (Array.map Int64.of_int [| a; b |])) in
v.(0), v.(1);;
</syntaxhighlight>
Testing
<
# open Blocks;;
Line 4,572:
# plus 0 0;;
- : int * int = (0, 0)
</syntaxhighlight>
An extension : n-bit adder, for n <= 64 (n could be greater, but we use Int64 for I/O)
<
(* general adder (n bits with n <= 64) *)
let gen_adder n = block_array serial [|
Line 4,591:
(eval (gadd_io n) n n (Array.map Int64.of_int [| a; b |])) in
v.(0), v.(1);;
</syntaxhighlight>
And a test
<
# gen_plus 7 100 100;;
- : int * int = (72, 1)
# gen_plus 8 100 100;;
- : int * int = (200, 0)
</syntaxhighlight>
=={{header|PARI/GP}}==
<
halfadd(a,b)=[a&&b,xor(a,b)];
fulladd(a,b,c)=my(t=halfadd(a,c),s=halfadd(t[2],b));[t[1]||s[1],s[2]];
Line 4,614:
[s3[1],s3[2],s2[2],s1[2],s0[2]]
};
add4(0,0,0,0,0,0,0,0)</
=={{header|Perl}}==
<
sub bin2dec { oct "0b".shift }
sub bin2bits { reverse split(//, substr(shift,0,shift)); }
Line 4,659:
$a, $b, $abin, $bbin, $c, $s, bin2dec($c.$s);
}
}</
Output matches the [[Four bit adder#Ruby|Ruby]] output.
=={{header|Phix}}==
<!--<
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">xor_gate</span><span style="color: #0000FF;">(</span><span style="color: #004080;">bool</span> <span style="color: #000000;">a</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">bool</span> <span style="color: #000000;">b</span><span style="color: #0000FF;">)</span>
Line 4,714:
<span style="color: #000000;">test</span><span style="color: #0000FF;">(</span><span style="color: #000000;">0b1101</span><span style="color: #0000FF;">,</span><span style="color: #000000;">0b0010</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">test</span><span style="color: #0000FF;">(</span><span style="color: #000000;">0b1101</span><span style="color: #0000FF;">,</span><span style="color: #000000;">0b0011</span><span style="color: #0000FF;">)</span>
<!--</
{{out}}
<pre>
Line 4,733:
=={{header|PicoLisp}}==
<
(cons
(and A B)
Line 4,755:
(cdr Fa3)
(cdr Fa2)
(cdr Fa1) ) ) )</
{{out}}
<pre>: (4bitsAdder NIL NIL NIL T NIL NIL NIL T)
Line 4,770:
=={{header|PL/I}}==
<syntaxhighlight lang="pl/i">
/* 4-BIT ADDER */
Line 4,806:
END TEST;
</syntaxhighlight>
=={{header|PowerShell}}==
===Using Bytes as Inputs===
<
{
$out1 = $a -band ( -bnot $b )
Line 4,861:
FourBitAdder 0xC 0xB
[Convert]::ToByte((FourBitAdder 0xC 0xB)["S"],2)</
===Translation of C# code===
The well-written C# code on this page can be translated without any modification into a .NET type by PowerShell.
<syntaxhighlight lang="powershell">
$source = @'
using System;
Line 4,997:
Add-Type -TypeDefinition $source -Language CSharpVersion3
</syntaxhighlight>
<syntaxhighlight lang="powershell">
[RosettaCodeTasks.FourBitAdder.ConstructiveBlocks]::Test()
</syntaxhighlight>
{{Out}}
<pre>
Line 5,017:
=={{header|Prolog}}==
Using hi/lo symbols to represent binary. As this is a simulation, there is no real "arithmetic" happening.
<
b_not(in(hi), out(lo)) :- !. % not(1) = 0
Line 5,058:
test_add(in(hi,hi,lo,hi), in(hi,lo,lo,hi), '11 + 9 = 20'),
test_add(in(lo,lo,lo,hi), in(lo,lo,lo,hi), '8 + 8 = 16'),
test_add(in(hi,hi,hi,hi), in(hi,lo,lo,lo), '15 + 1 = 16').</
<pre>?- go.
in(hi,lo,lo,lo) + in(hi,lo,lo,lo) is out(lo,hi,lo,lo) c(lo) (1 + 1 = 2)
Line 5,069:
=={{header|PureBasic}}==
<
;Output values from the constructive building blocks is done using pointers (i.e. '*').
Line 5,122:
Input()
CloseConsole()
EndIf</
{{out}}
<pre>0110 + 1110 = 0100 overflow 1</pre>
Line 5,144:
between the normal Python values and those of the simulation.
<
def ha(a, b): return xor(a, b), a and b # sum, carry
Line 5,178:
if __name__ == '__main__':
test_fa4()</
=={{header|Racket}}==
<
(define (adder-and a b)
Line 5,226:
(cons v 4s))))
(n-bit-adder '(1 0 1 0) '(0 1 1 1)) ;-> '(1 0 0 0 1)</
=={{header|Raku}}==
(formerly Perl 6)
<syntaxhighlight lang="raku"
sub half-adder ($a, $b) {
Line 5,257:
is four-bit-adder(1, 0, 1, 0, 1, 0, 1, 0), (0, 1, 0, 1, 0), '5 + 5 == 10';
is four-bit-adder(1, 0, 0, 1, 1, 1, 1, 0)[4], 1, '7 + 9 == overflow';
}</
{{out}}
Line 5,271:
::::* the '''|''' symbol is a logical '''OR'''.
::::* the '''&''' symbol is a logical '''AND'''.
<
call hdr1; call hdr2 /*note the order of headers & trailers.*/
/* [↓] traipse thru all possibilities.*/
Line 5,301:
do j=0 for 4; n= j - 1
s.j= fullAdder(a.j, b.j, carry.n); carry.j= c
end /*j*/; return c</
{{out|output|text= (most lines have been elided):}}
<pre style="height:63ex">
Line 5,374:
{{Full One-Bit-Adder function is made up of XOR OR AND gates}}
<
###---------------------------
Line 5,446:
###------------------------
</syntaxhighlight>
Output:
<pre>
Line 5,461:
=={{header|Ruby}}==
<
def four_bit_adder(a, b)
a_bits = binary_string_to_bits(a,4)
Line 5,516:
[a, b, bin_a, bin_b, carry, sum, (carry + sum).to_i(2)]
end
end</
{{out}}
Line 5,540:
=={{header|Rust}}==
<
// half adder with XOR and AND
// SUM = A XOR B
Line 5,605:
}
</syntaxhighlight>
=={{header|Sather}}==
<
-- that "sets" it to 0 or 1, while it can be "read"
-- ad libitum. (Tristate logic is not taken into account)
Line 5,745:
", overflow = " + fba.v.val + "\n";
end;
end;</
=={{header|Scala}}==
<
type Nibble=(Boolean, Boolean, Boolean, Boolean)
Line 5,773:
((s3, s2, s1, s0), cOut)
}
}</
A test program using the object above.
<
import FourBitAdder._
def main(args: Array[String]): Unit = {
Line 5,790:
implicit def intToNibble(i:Int):Nibble=((i>>>3)&1, (i>>>2)&1, (i>>>1)&1, i&1)
def nibbleToString(n:Nibble):String="%d%d%d%d".format(n._1.toInt, n._2.toInt, n._3.toInt, n._4.toInt)
}</
{{out}}
<pre> A B S C
Line 5,809:
{{trans|Common Lisp}}
<
(import (scheme base)
(scheme write)
Line 5,843:
(show-eg (list 1 1 1 1) (list 1 1 1 1))
(show-eg (list 1 0 1 0) (list 0 1 0 1))
</syntaxhighlight>
{{out}}
Line 5,858:
This is full adder that means it takes arbitrary number of bits (think of it as infinite stack of 2 bit adders, which is btw how it's internally made).
I took it from https://github.com/emsi/SedScripts
<
#!/bin/sed -f
# (C) 2005,2014 by Mariusz Woloszyn :)
Line 5,910:
}
b LOOP</
Example usage:
<
./binAdder.sed
1111110111
Line 5,929:
0 0 0 1
111
</syntaxhighlight>
=={{header|Sidef}}==
{{trans|Perl}}
<
(~a & b) | (a & ~b)
}
Line 5,963:
a, b, abin.join, bbin.join, c, s, "#{c}#{s}".bin)
}
}</
{{out}}
Line 5,989:
=={{header|Swift}}==
<
func halfAdder(_ a: Int, _ b: Int) -> (Int, Int) {
Line 6,016:
print("\(a) + \(b) = \(fourBitAdder(a, b))")
</syntaxhighlight>
{{out}}
Line 6,024:
=={{header|SystemVerilog}}==
In SystemVerilog we can define a multibit adder as a parameterized module, that instantiates the components:
<syntaxhighlight lang="systemverilog">
module Half_Adder( input a, b, output s, c );
assign s = a ^ b;
Line 6,058:
endmodule
</syntaxhighlight>
And then a testbench to test it -- here I use random stimulus with an assertion (it's aften good to separate the stimulus generation from the results-checking):
<syntaxhighlight lang="systemverilog">
module simTop();
Line 6,094:
endprogram
</syntaxhighlight>
{{out}}
Line 6,128:
=={{header|Tcl}}==
This example shows how you can make little languages in Tcl that describe the problem space.
<
# Create our little language
Line 6,192:
fulladd a2 b2 c2 s2 c3
fulladd a3 b3 c3 s3 v
}</
<
proc 4add_driver {a b} {
lassign [split $a {}] a3 a2 a1 a0
Line 6,206:
set a 1011
set b 0110
puts $a+$b=[4add_driver $a $b]</
{{out}}
<pre>
Line 6,216:
=={{header|TorqueScript}}==
<
{
return (!%a && %b) || (%a && !%b);
Line 6,244:
%r3 = FullAdd(%a3, %b3, getWord(%r2, 0));
return getWord(%r0,1) SPC getWord(%r1,1) SPC getWord(%r2,1) SPC getWord(%r3,1) SPC getWord(%r3,0);
}</
=={{header|UNIX Shell}}==
Line 6,254:
Bash and zsh allow the snake_case function names to be replaced with kebab-case; ksh does not. The use of the <tt>typeset</tt> synonym for <tt>local</tt> is also in order to achieve ksh compatibility.
<
typeset -i a=$1 b=$2
printf '%d\n' $(( (a || b) && ! (a && b) ))
Line 6,299:
is "7 + 9 = overflow" "a=($(four_bit_adder 1 0 0 1 1 1 1 0)); (( \${a[-1]}==1 ))"
</syntaxhighlight>
{{Out}}
Line 6,308:
=={{header|Verilog}}==
In Verilog we can also define a multibit adder as a component with multiple instances:
<syntaxhighlight lang="verilog">
module Half_Adder( output c, s, input a, b );
xor xor01 (s, a, b);
Line 6,357:
endmodule // test_Full_Adder
</syntaxhighlight>
{{out}}
Line 6,372:
=={{header|VHDL}}==
The following is a direct implementation of the proposed schematic:
<
USE ieee.std_logic_1164.all;
Line 6,532:
begin
x <= (a and not b) or (b and not a);
end architecture rtl;</
An exhaustive testbench:
<
USE ieee.std_logic_1164.all;
use ieee.NUMERIC_STD.all;
Line 6,580:
);
end struct;</
=={{header|Wren}}==
{{trans|Go}}
<
var ha = Fn.new { |a, b| [xor.call(a, b), a & b] }
Line 6,610:
}
System.print(add4.call(1, 0, 1, 0, 1, 0, 0, 1))</
{{out}}
Line 6,618:
=={{header|XPL0}}==
<
func Not(A);
Line 6,676:
Add4Bits(1, 1, 1, 1, 1, 1, 1, 1, @S0, @S1, @S2, @S3, @C); \1111 + 1111 = 11110
BinOut(0, S0, S1, S2, S3, C); CrLf(0);
]</
{{out}}
Line 6,686:
=={{header|zkl}}==
<
{ a.bitAnd(b.bitNot()).bitOr(b.bitAnd(a.bitNot())) }
Line 6,709:
// add(10,9) result should be 1 0 0 1 1 (0x13, 3 carry 1)
println(fourBitAdder(1,0,1,0, 1,0,0,1));</
<
(ss:=List()).append(
[as.len()-1 .. 0,-1].reduce('wrap(c,n){
Line 6,717:
.reverse();
}
println(nBitAddr(T(1,0,1,0), T(1,0,0,1)));</
{{out}}
<pre>
|