Jump to content

Four bit adder: Difference between revisions

m
syntax highlighting fixup automation
m (→‎{{header|UNIX Shell}}: FIx spelling of "adder.")
m (syntax highlighting fixup automation)
Line 43:
{{trans|Python}}
 
<langsyntaxhighlight lang="11l">F xor(a, b)
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)))</langsyntaxhighlight>
 
=={{header|Action!}}==
<langsyntaxhighlight Actionlang="action!">DEFINE Bit="BYTE"
 
TYPE FourBit=[Bit b0,b1,b2,b3]
Line 141:
PrintBE(c)
OD
RETURN</langsyntaxhighlight>
{{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">
<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>
</lang>
A test program with the above definitions
<syntaxhighlight lang="ada">
<lang Ada>
with Ada.Text_IO; use Ada.Text_IO;
 
Line 247:
end loop;
end Test_4_Bit_Adder;
</syntaxhighlight>
</lang>
{{out}}
<div style="height: 320px;overflow:scroll">
Line 513:
{{works with|Dyalog APL}}
{{works with|GNU APL}}
<langsyntaxhighlight lang="apl">⍝ Our primitive "gates" are built-in, but let's give them names
not ← { ~ ⍵ } ⍝ in Dyalog these assignments can be simplified to "not ← ~", "and ← ∧", etc.
and ← { ⍺ ∧ ⍵ }
Line 553:
⍝ And go
{ (randbits 4) demo randbits 4 ⊣ ⍵ } ¨ ⍳20
</syntaxhighlight>
</lang>
 
{{Out}}
Line 580:
=={{header|AutoHotkey}}==
{{works with|AutoHotkey 1.1}}
<langsyntaxhighlight AutoHotkeylang="autohotkey">A := 13
B := 9
N := FourBitAdd(A, B)
Line 621:
Res := Mod(N, 2) Res, N := N >> 1
return, Res
}</langsyntaxhighlight>
{{out}}
<pre>13 + 9:
Line 628:
=={{header|AutoIt}}==
===Functions===
<syntaxhighlight lang="autoit">
<lang AutoIt>
Func _NOT($_A)
Return (Not $_A) *1
Line 669:
Return $Q4 & $Q3 & $Q2 & $Q1
EndFunc ;==>_4BitAdder
</syntaxhighlight>
</lang>
===Example===
<syntaxhighlight lang="autoit">
<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>
</lang>
{{out}}
<pre>
Line 690:
==={{header|Applesoft BASIC}}===
 
<langsyntaxhighlight lang="basic">100 S$ = "1100 + 1100 = " : GOSUB 400
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</langsyntaxhighlight>
 
==={{header|BBC BASIC}}===
{{works with|BBC BASIC for Windows}}
<langsyntaxhighlight lang="bbcbasic"> @% = 2
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&</langsyntaxhighlight>
{{out}}
<pre>
Line 811:
 
=={{header|Batch File}}==
<langsyntaxhighlight lang="dos">
@echo off
setlocal enabledelayedexpansion
Line 948:
if %1==1 if %2==1 exit /b 1
exit /b 0
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 957:
 
=={{header|C}}==
<langsyntaxhighlight lang="c">#include <stdio.h>
 
typedef char pin_t;
Line 1,026:
return 0;
}</langsyntaxhighlight>
 
=={{header|C sharp|C#}}==
 
{{works with|C sharp|C#|3+}}
<langsyntaxhighlight lang="csharp">
using System;
using System.Collections.Generic;
Line 1,160:
}
 
</syntaxhighlight>
</lang>
 
=={{header|C++}}==
Line 1,166:
 
=={{header|Clojure}}==
<langsyntaxhighlight lang="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>
</lang>
 
===Second Clojure solution===
<langsyntaxhighlight lang="clojure">(ns rosetta.fourbit)
 
;; a bit is represented as a boolean (true/false)
Line 1,256:
)
 
</syntaxhighlight>
</lang>
 
===Using Bitwise Operators===
<langsyntaxhighlight lang="clojure">
(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>
</lang>
 
=={{header|COBOL}}==
<syntaxhighlight lang="cobol">
<lang COBOL>
program-id. test-add.
environment division.
Line 1,405:
end program add-4b.
 
</syntaxhighlight>
</lang>
{{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.
 
<langsyntaxhighlight lang="coffeescript">
# 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>
</lang>
 
=={{header|Common Lisp}}==
<langsyntaxhighlight lang="lisp">;; returns a list of bits: '(sum carry)
(defun half-adder (a b)
(list (logxor a b) (logand a b)))
Line 1,495:
 
(main)
</syntaxhighlight>
</lang>
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.
<langsyntaxhighlight lang="d">import std.stdio, std.traits;
 
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);
}</langsyntaxhighlight>
{{out}}
<pre> a3 00000000000000000000000000000000
Line 1,592:
overflow 11111111111111111111111111111111</pre>
128 4-bit adds in parallel:
<langsyntaxhighlight lang="d">import std.stdio, std.traits, core.simd;
 
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);
}</langsyntaxhighlight>
{{out}}
<pre> a3 00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
Line 1,675:
overflow 11111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111</pre>
Compiled by the ldc2 compiler to (where T = ubyte32, 256 adds using AVX2):
<langsyntaxhighlight lang="asm">fourBitsAdder:
pushl %ebp
movl %esp, %ebp
Line 1,713:
popl %ebp
vzeroupper
ret $160</langsyntaxhighlight>
=={{header|Delphi}}==
{{libheader| System.SysUtils}}
{{Trans|C#}}
<syntaxhighlight lang="delphi">
<lang Delphi>
program Four_bit_adder;
 
Line 1,896:
Readln;
end.
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 2,159:
{{works with|Elixir|1.1}}
{{trans|Ruby}}
<langsyntaxhighlight lang="elixir">defmodule RC do
use Bitwise
@bit_size 4
Line 2,205:
end
 
RC.task</langsyntaxhighlight>
 
{{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">
<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>
</lang>
{{out}}
<pre>
Line 2,310:
 
=={{header|F_Sharp|F#}}==
<langsyntaxhighlight lang="fsharp">
type Bit =
| Zero
Line 2,347:
printfn "0001 + 0111 ="
b4A (Zero, Zero, Zero, One) (Zero, One, One, One) |> printfn "%A"
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 2,355:
 
=={{header|Forth}}==
<langsyntaxhighlight lang="forth">: "NOT" invert 1 and ;
: "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 ;</langsyntaxhighlight>
{{out}}
<pre>1 1 0 0 0 0 1 1 .add4 01111
Line 2,373:
=={{header|Fortran}}==
{{works with|Fortran|90 and later}}
<langsyntaxhighlight lang="fortran">module logic
implicit none
 
Line 2,449:
end do
end do
end program</langsyntaxhighlight>
{{out}} (selected)
<pre>1100 + 1100 = 11000
Line 2,469:
 
=={{header|FreeBASIC}}==
<langsyntaxhighlight lang="freebasic">sub half_add( byval a as ubyte, byval b as ubyte,_
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</langsyntaxhighlight>
{{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.
<langsyntaxhighlight lang="go">package main
 
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))
}</langsyntaxhighlight>
{{out}}
<pre>
Line 2,555:
===Channels===
Alternative solution is a little more like a simulation.
<langsyntaxhighlight lang="go">package main
 
import "fmt"
Line 2,680:
B[<-r4], B[<-r3], B[<-r2], B[<-r1], B[<-carry])
}
</syntaxhighlight>
</lang>
 
Mini reference:
Line 2,689:
 
=={{header|Groovy}}==
<langsyntaxhighlight Groovylang="groovy">class Main {
static void main(args) {
 
Line 2,915:
adder4.setBit2 input
}
}</langsyntaxhighlight>
 
=={{header|Haskell}}==
Basic gates:
<langsyntaxhighlight lang="haskell">import Control.Arrow
import Data.List (mapAccumR)
 
Line 2,926:
band = min
bnot :: Int -> Int
bnot = (1-)</langsyntaxhighlight>
Gates built with basic ones:
<langsyntaxhighlight lang="haskell">nand, xor :: Int -> Int -> Int
nand = (bnot.).band
xor a b = uncurry nand. (nand a &&& nand b) $ nand a b</langsyntaxhighlight>
Adder circuits:
<langsyntaxhighlight lang="haskell">halfAdder = uncurry band &&& uncurry xor
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</langsyntaxhighlight>
 
Example using adder4
<langsyntaxhighlight lang="haskell">*Main> adder4 [1,0,1,0] [1,1,1,1]
(1,[1,0,0,1])</langsyntaxhighlight>
 
=={{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.
 
<langsyntaxhighlight lang="unicon">#
# 4bitadder.icn, emulate a 4 bit adder. Using only and, or, not
#
Line 3,047:
# cr.c is the overflow carry
return s
end</langsyntaxhighlight>
 
{{out}}
Line 3,075:
 
===Implementation===
<langsyntaxhighlight lang="j">and=: *.
or=: +.
not=: -.
xor=: (and not) or (and not)~
hadd=: and ,"0 xor
add=: ((({.,0:)@[ or {:@[ hadd {.@]), }.@])/@hadd</langsyntaxhighlight>
 
===Example use===
<langsyntaxhighlight lang="j"> 1 1 1 1 add 0 1 1 1
1 0 1 1 0</langsyntaxhighlight>
 
To produce all results:
<langsyntaxhighlight lang="j"> add"1/~#:i.16</langsyntaxhighlight>
 
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:
 
<langsyntaxhighlight lang="j"> ,"2 ' ',"1 -.&' '@":"1 add"1/~#:i.16
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</langsyntaxhighlight>
 
Alternatively, the fact that add was designed to operate on lists of bits could have been incorporated into its definition:
 
<langsyntaxhighlight lang="j">add=: ((({.,0:)@[ or {:@[ hadd {.@]), }.@])/@hadd"1</langsyntaxhighlight>
 
Then to get all results you could use:
<langsyntaxhighlight lang="j"> add/~#:i.16</langsyntaxhighlight>
 
Compare this to a regular addition table:
<syntaxhighlight lang ="j"> +/~i.10</langsyntaxhighlight>
(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}}==
 
<langsyntaxhighlight lang="java">public class GateLogic
{
// Basic gate interfaces
Line 3,303:
}
}</langsyntaxhighlight>
 
{{out}}
Line 3,320:
0s and 1s. To enforce this, we'll first create a couple of helper functions.
 
<syntaxhighlight lang="javascript">
<lang JavaScript>
function acceptedBinFormat(bin) {
if (bin == 1 || bin === 0 || bin === '0')
Line 3,335:
return true;
}
</syntaxhighlight>
</lang>
 
===Implementation===
Line 3,342:
and, finally, the four bit adder.
 
<syntaxhighlight lang="javascript">
<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>
</lang>
===Example Use===
<langsyntaxhighlight JavaScriptlang="javascript">fourBitAdder('1010', '0101'); // 1111 (15)</langsyntaxhighlight>
 
all results:
 
<syntaxhighlight lang="javascript">
<lang JavaScript>
// run this in your browsers console
var outer = inner = 16, a, b;
Line 3,433:
inner = outer;
}
</syntaxhighlight>
</lang>
 
=={{header|jq}}==
Line 3,440:
All the operations except fourBitAdder(a,b) assume the inputs are presented as 0 or 1 (i.e. integers).
 
<langsyntaxhighlight lang="jq"># Start with the 'not' and 'and' building blocks.
# 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("") ;</langsyntaxhighlight>
'''Example:'''
<langsyntaxhighlight lang="jq">fourBitAdder("0111"; "0001")</langsyntaxhighlight>
{{out}}
$ jq -n -f Four_bit_adder.jq
Line 3,490:
=={{header|Jsish}}==
Based on Javascript entry.
<langsyntaxhighlight lang="javascript">#!/usr/bin/env jsish
/* 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!=
*/</langsyntaxhighlight>
{{out}}
<pre>prompt$ jsish --U fourBitAdder.jsi
Line 3,594:
 
'''Functions'''
<langsyntaxhighlight Julialang="julia">using Printf
 
xor{T<:Bool}(a::T, b::T) = (a&~b)|(~a&b)
Line 3,624:
 
Base.bits(n::BitArray{1}) = join(reverse(int(n)), "")
</syntaxhighlight>
</lang>
 
'''Main'''
<syntaxhighlight lang="julia">
<lang Julia>
xavail = trues(15,15)
xcnt = 0
Line 3,646:
bits(s), oflow))
end
</syntaxhighlight>
</lang>
 
{{out}}
Line 3,664:
 
=={{header|Kotlin}}==
<langsyntaxhighlight lang="scala">// version 1.1.51
 
val Boolean.I get() = if (this) 1 else 0
Line 3,715:
for (j in i..minOf(i + 1, 15)) test(i, j)
}
}</langsyntaxhighlight>
 
{{out}}
Line 3,771:
 
=={{header|Lambdatalk}}==
<syntaxhighlight lang="scheme">
<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>
</lang>
 
=={{header|Lua}}==
<langsyntaxhighlight Lualang="lua">-- Build XOR from AND, OR and NOT
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)</langsyntaxhighlight>
Output:
<pre>SUM OVERFLOW
Line 3,931:
 
=={{header|M2000 Interpreter}}==
<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
Module FourBitAdder {
Flush
Line 3,991:
}
FourBitAdder
</syntaxhighlight>
</lang>
 
=={{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}];</langsyntaxhighlight>
Example:
<syntaxhighlight lang="text">fourbitadder[{1, 0, 1, 0}, {1, 1, 1, 1}]</langsyntaxhighlight>
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.
 
<langsyntaxhighlight MATLABlang="matlab">function [S,v] = fourBitAdder(input1,input2)
 
%Make sure that only 4-Bit numbers are being added. This assumes that
Line 4,081:
v = num2str(v);
end
end %fourBitAdder</langsyntaxhighlight>
 
Sample Usage:
<langsyntaxhighlight MATLABlang="matlab">>> [S,V] = fourBitAdder([0 0 0 1],[1 1 1 1])
 
S =
Line 4,137:
 
11
12</langsyntaxhighlight>
 
=={{header|MUMPS}}==
<langsyntaxhighlight MUMPSlang="mumps">XOR(Y,Z) ;Uses logicals - i.e., 0 is false, anything else is true (1 is used if setting a value)
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</langsyntaxhighlight>
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.
 
<langsyntaxhighlight lang="python">"""
To run:
python3 Four_bit_adder_011.py
Line 4,311:
if __name__ == '__main__':
main()
</syntaxhighlight>
</lang>
 
=={{header|Nim}}==
{{trans|Python}}
<langsyntaxhighlight lang="nim">type
 
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))</langsyntaxhighlight>
 
=={{header|OCaml}}==
<langsyntaxhighlight lang="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>
</lang>
 
Testing
 
<langsyntaxhighlight lang="ocaml">
# open Blocks;;
 
Line 4,572:
# plus 0 0;;
- : int * int = (0, 0)
</syntaxhighlight>
</lang>
 
An extension : n-bit adder, for n <= 64 (n could be greater, but we use Int64 for I/O)
 
<langsyntaxhighlight lang="ocaml">
(* 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>
</lang>
 
And a test
 
<langsyntaxhighlight lang="ocaml">
# gen_plus 7 100 100;;
- : int * int = (72, 1)
# gen_plus 8 100 100;;
- : int * int = (200, 0)
</syntaxhighlight>
</lang>
 
=={{header|PARI/GP}}==
<langsyntaxhighlight lang="parigp">xor(a,b)=(!a&b)||(a&!b);
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)</langsyntaxhighlight>
 
=={{header|Perl}}==
<langsyntaxhighlight lang="perl">sub dec2bin { sprintf "%04b", shift }
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);
}
}</langsyntaxhighlight>
 
Output matches the [[Four bit adder#Ruby|Ruby]] output.
 
=={{header|Phix}}==
<!--<langsyntaxhighlight Phixlang="phix">(phixonline)-->
<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>
<!--</langsyntaxhighlight>-->
{{out}}
<pre>
Line 4,733:
 
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="picolisp">(de halfAdder (A B) #> (Carry . Sum)
(cons
(and A B)
Line 4,755:
(cdr Fa3)
(cdr Fa2)
(cdr Fa1) ) ) )</langsyntaxhighlight>
{{out}}
<pre>: (4bitsAdder NIL NIL NIL T NIL NIL NIL T)
Line 4,770:
 
=={{header|PL/I}}==
<syntaxhighlight lang="pl/i">
<lang PL/I>
/* 4-BIT ADDER */
 
Line 4,806:
 
END TEST;
</syntaxhighlight>
</lang>
 
=={{header|PowerShell}}==
===Using Bytes as Inputs===
<langsyntaxhighlight Powershelllang="powershell">function bxor2 ( [byte] $a, [byte] $b )
{
$out1 = $a -band ( -bnot $b )
Line 4,861:
FourBitAdder 0xC 0xB
 
[Convert]::ToByte((FourBitAdder 0xC 0xB)["S"],2)</langsyntaxhighlight>
 
===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">
<lang PowerShell>
$source = @'
using System;
Line 4,997:
 
Add-Type -TypeDefinition $source -Language CSharpVersion3
</syntaxhighlight>
</lang>
<syntaxhighlight lang="powershell">
<lang PowerShell>
[RosettaCodeTasks.FourBitAdder.ConstructiveBlocks]::Test()
</syntaxhighlight>
</lang>
{{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.
<langsyntaxhighlight lang="prolog">% binary 4 bit adder chip simulation
 
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').</langsyntaxhighlight>
<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}}==
<langsyntaxhighlight PureBasiclang="purebasic">;Because no representation for a solitary bit is present, bits are stored as bytes.
;Output values from the constructive building blocks is done using pointers (i.e. '*').
 
Line 5,122:
Input()
CloseConsole()
EndIf</langsyntaxhighlight>
{{out}}
<pre>0110 + 1110 = 0100 overflow 1</pre>
Line 5,144:
between the normal Python values and those of the simulation.
<langsyntaxhighlight lang="python">def xor(a, b): return (a and not b) or (b and not a)
 
def ha(a, b): return xor(a, b), a and b # sum, carry
Line 5,178:
 
if __name__ == '__main__':
test_fa4()</langsyntaxhighlight>
 
=={{header|Racket}}==
<langsyntaxhighlight Racketlang="racket">#lang 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)</langsyntaxhighlight>
 
=={{header|Raku}}==
(formerly Perl 6)
<syntaxhighlight lang="raku" perl6line>sub xor ($a, $b) { (($a and not $b) or (not $a and $b)) ?? 1 !! 0 }
 
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';
}</langsyntaxhighlight>
 
{{out}}
Line 5,271:
::::* the &nbsp; &nbsp; '''|''' &nbsp; &nbsp; &nbsp; symbol is a logical '''OR'''.
::::* the &nbsp; &nbsp; '''&amp;''' &nbsp; &nbsp; symbol is a logical '''AND'''.
<langsyntaxhighlight lang="rexx">/*REXX program displays (all) the sums of a full 4─bit adder (with carry). */
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</langsyntaxhighlight>
{{out|output|text=&nbsp; &nbsp; (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}}
 
<langsyntaxhighlight lang="ring">
 
###---------------------------
Line 5,446:
###------------------------
 
</syntaxhighlight>
</lang>
Output:
<pre>
Line 5,461:
 
=={{header|Ruby}}==
<langsyntaxhighlight lang="ruby"># returns pair [sum, carry]
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</langsyntaxhighlight>
 
{{out}}
Line 5,540:
 
=={{header|Rust}}==
<langsyntaxhighlight lang="rust">
// half adder with XOR and AND
// SUM = A XOR B
Line 5,605:
}
 
</syntaxhighlight>
</lang>
 
=={{header|Sather}}==
<langsyntaxhighlight lang="sather">-- a "pin" can be connected only to one component
-- 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;</langsyntaxhighlight>
 
=={{header|Scala}}==
<langsyntaxhighlight lang="scala">object FourBitAdder {
type Nibble=(Boolean, Boolean, Boolean, Boolean)
 
Line 5,773:
((s3, s2, s1, s0), cOut)
}
}</langsyntaxhighlight>
 
A test program using the object above.
<langsyntaxhighlight lang="scala">object FourBitAdderTest {
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)
}</langsyntaxhighlight>
{{out}}
<pre> A B S C
Line 5,809:
{{trans|Common Lisp}}
 
<langsyntaxhighlight lang="scheme">
(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>
</lang>
 
{{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
<langsyntaxhighlight lang="sed">
#!/bin/sed -f
# (C) 2005,2014 by Mariusz Woloszyn :)
Line 5,910:
}
 
b LOOP</langsyntaxhighlight>
 
Example usage:
 
<langsyntaxhighlight lang="sed">
./binAdder.sed
1111110111
Line 5,929:
0 0 0 1
111
</syntaxhighlight>
</lang>
 
=={{header|Sidef}}==
{{trans|Perl}}
<langsyntaxhighlight lang="ruby">func bxor(a, b) {
(~a & b) | (a & ~b)
}
Line 5,963:
a, b, abin.join, bbin.join, c, s, "#{c}#{s}".bin)
}
}</langsyntaxhighlight>
 
{{out}}
Line 5,989:
=={{header|Swift}}==
 
<langsyntaxhighlight lang="swift">typealias FourBit = (Int, Int, Int, Int)
 
func halfAdder(_ a: Int, _ b: Int) -> (Int, Int) {
Line 6,016:
print("\(a) + \(b) = \(fourBitAdder(a, b))")
 
</syntaxhighlight>
</lang>
 
{{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">
<lang SystemVerilog>
module Half_Adder( input a, b, output s, c );
assign s = a ^ b;
Line 6,058:
 
endmodule
</syntaxhighlight>
</lang>
 
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">
<lang SystemVerilog>
module simTop();
 
Line 6,094:
endprogram
 
</syntaxhighlight>
</lang>
 
{{out}}
Line 6,128:
=={{header|Tcl}}==
This example shows how you can make little languages in Tcl that describe the problem space.
<langsyntaxhighlight lang="tcl">package require Tcl 8.5
 
# Create our little language
Line 6,192:
fulladd a2 b2 c2 s2 c3
fulladd a3 b3 c3 s3 v
}</langsyntaxhighlight>
 
<langsyntaxhighlight lang="tcl"># Simple driver for the circuit
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]</langsyntaxhighlight>
{{out}}
<pre>
Line 6,216:
 
=={{header|TorqueScript}}==
<langsyntaxhighlight Torquelang="torque">function XOR(%a, %b)
{
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);
}</langsyntaxhighlight>
 
=={{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.
 
<langsyntaxhighlight lang="sh">xor() {
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>
</lang>
 
{{Out}}
Line 6,308:
=={{header|Verilog}}==
In Verilog we can also define a multibit adder as a component with multiple instances:
<syntaxhighlight lang="verilog">
<lang Verilog>
module Half_Adder( output c, s, input a, b );
xor xor01 (s, a, b);
Line 6,357:
 
endmodule // test_Full_Adder
</syntaxhighlight>
</lang>
 
{{out}}
Line 6,372:
=={{header|VHDL}}==
The following is a direct implementation of the proposed schematic:
<langsyntaxhighlight VHDLlang="vhdl">LIBRARY ieee;
USE ieee.std_logic_1164.all;
 
Line 6,532:
begin
x <= (a and not b) or (b and not a);
end architecture rtl;</langsyntaxhighlight>
 
 
An exhaustive testbench:
<langsyntaxhighlight VHDLlang="vhdl">LIBRARY ieee;
USE ieee.std_logic_1164.all;
use ieee.NUMERIC_STD.all;
Line 6,580:
);
 
end struct;</langsyntaxhighlight>
 
=={{header|Wren}}==
{{trans|Go}}
<langsyntaxhighlight lang="ecmascript">var xor = Fn.new { |a, b| a&(~b) | b&(~a) }
 
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))</langsyntaxhighlight>
 
{{out}}
Line 6,618:
 
=={{header|XPL0}}==
<langsyntaxhighlight XPL0lang="xpl0">code CrLf=9, IntOut=11;
 
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);
]</langsyntaxhighlight>
 
{{out}}
Line 6,686:
 
=={{header|zkl}}==
<langsyntaxhighlight lang="zkl">fcn xor(a,b) // a,b are 1|0 -->a^b(1|0)
{ 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));</langsyntaxhighlight>
<langsyntaxhighlight lang="zkl">fcn nBitAddr(as,bs){ //-->(carry, sn..s3,s2,s1,s0)
(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)));</langsyntaxhighlight>
{{out}}
<pre>
10,333

edits

Cookies help us deliver our services. By using our services, you agree to our use of cookies.