Tuesday, 11 July 2017

Full Adder and Half Adder




package com.johnny.adder;

/**
 *
 * @author johnny
 */
public class Adder {

static public AdderResult halfAdder(int a, int b) {
return new AdderResult(a ^ b, a & b);
}

static public AdderResult fullAdder(int a, int b, int carryIn) {
AdderResult res1 = halfAdder(a, b);
AdderResult res2 = halfAdder(res1.getSum(), carryIn);

return new AdderResult(res2.getSum(), res1.getCarry() | res2.getCarry());
}

}


package com.johnny.adder;

/**
 *
 * @author johnny
 */
public class AdderResult {

private int sum;
private int carry;

public AdderResult(int sum, int carry) {
this.sum = sum;
this.carry = carry;
}

public int getSum() {
return sum;
}

public void setSum(int sum) {
this.sum = sum;
}

public int getCarry() {
return carry;
}

public void setCarry(int carry) {
this.carry = carry;
}

@Override
public String toString() {
return " sum " + getSum() + " carry " + getCarry();
}
}




package com.johnny.adder;

import com.johnny.app.AppException;
import com.johnny.app.AppInf;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author johnny
 */
public class App implements AppInf {

@Override
public String getTitle() {
return "Full Adder";
}

@Override
public void execute(String[] args) {

assertAdder(Adder.fullAdder(0, 0, 0), 0, 0);
assertAdder(Adder.fullAdder(0, 1, 0), 1, 0);
assertAdder(Adder.fullAdder(1, 0, 0), 1, 0);
assertAdder(Adder.fullAdder(1, 1, 0), 0, 1);

assertAdder(Adder.fullAdder(0, 0, 1), 1, 0);
assertAdder(Adder.fullAdder(0, 1, 1), 0, 1);
assertAdder(Adder.fullAdder(1, 0, 1), 0, 1);
assertAdder(Adder.fullAdder(1, 1, 1), 1, 1);

for (int i = -8192; i < 8192; i++) {
for (int j = -8192; j < 8192; j++) {
try {
assertCond((add(i, j) == (i + j)), " sum failed " + i + "+" + j);
} catch (Exception ex) {
Logger.getLogger(App.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}

public int add(int a, int b) {
int sum = 0;
int carryIn = 0;

//for each bit do fullAdder
for (int bitNumber = 0; bitNumber < 32; bitNumber++) {
if (a == 0 && b == 0 && carryIn == 0) {
break;
}
int abit = a & 1;
int bbit = b & 1;
AdderResult res = Adder.fullAdder(abit, bbit, carryIn);
sum |= (res.getSum() << bitNumber);
carryIn = res.getCarry();
a >>= 1;
b >>= 1;
}
return sum;
}

public void assertAdder(AdderResult result, int expectedSum, int expectedCarry) {

try {
assertCond(result.getSum() == expectedSum, "Sum not expected " + expectedSum + ":" + expectedCarry);
assertCond(result.getCarry() == expectedCarry, "Carry not expected " + expectedSum + ":" + expectedCarry);

} catch (AppException ex) {
Logger.getLogger(App.class.getName()).log(Level.SEVERE, null, ex);
}

}

public void assertCond(boolean condition, String failMessage) throws AppException {
if (!condition) {
throw new AppException(failMessage);
}
}

}


No comments:

Post a Comment