Four bit adder: Difference between revisions

More strict D version
(→‎{{header|Go}}: added simple solution)
(More strict D version)
Line 614:
<lang d>import std.stdio: writefln;
 
pure nothrow void fourBitsAdder(T)(in T a0, in T a1, in T a2, in T a3,
/// A XOR using only NOT, AND and OR, as task requires
T xor(T)( in T xb0, in T y)b1, {in returnT (~xb2, &in y) | (xT & ~y); }b3,
out T o0, out T o1, out T o2o0, out T o3o1,
T b0, T b1, out T b2o2, out T b3o3,
out T overflow) {
/ // A XOR using only NOT, AND and OR, as task requires
static pure nothrow T xor(in T x, in T y) {
return (~x & y) | (x & ~y);
}
 
static pure nothrow void halfAdder(T)(in T a, in T b, out T s, out T c) {
out T s, out T c) {
s = xor(a, b);
c s = xor(a &, b);
// s = a ^ b; // a natural XOR in D
}
s c = xor(a, & b);
}
 
static pure nothrow void fullAdder(T)(in T a, in T b, in T ic, out T s, out T oc) {
out T s, out T oc) {
T ps, pc, tc;
 
halfAdder(/*input*/a, b, /*output*/ps, pc);
halfAdder(/*input*/ps, ic, /*output*/s, tc);
oc = tc | pc;
}
}
 
void fourBitsAdder(T)(T a0, T a1, T a2, T a3,
T b0, T b1, T b2, T b3,
out T o0, out T o1, out T o2, out T o3,
out T overflow) {
T zero, tc0, tc1, tc2;
 
Line 645 ⟶ 651:
alias size_t T;
 
enum T one = T.max;,
enum T zero = T.min;,
T a3 a0 = zero;, T b3a1 = one;, a2 = zero, a3 = zero,
T a2 b0 = zero;, Tb1 = one, b2 = one, b3 = one;
T a1 = one; T b1 = one;
T a0 = zero; T b0 = zero;
T s0, s1, s2, s3, overflow;
 
fourBitsAdder(/*input*/ a0, a1, a2, a3,
/*input*/ b0, b1, b2, b3,
/*output*/ s0, s1, s2, s3, overflow);
 
writefln(" a3 %032b", a3);
Anonymous user