-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAdder.java
More file actions
66 lines (62 loc) · 2.86 KB
/
Adder.java
File metadata and controls
66 lines (62 loc) · 2.86 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
public class Adder {
// Subtract is built on add, essentially in that it turns b into a negative number, and then adds it to a in order to return a result.
public static void subtract(Word32 a, Word32 b, Word32 result) {
Word32 negativePre1 = new Word32();
b.copy(negativePre1);
negativePre1.not(negativePre1);
Word32 one = new Word32();
Bit bt = new Bit(true);
one.setBitN(31, bt);
Word32 negative = new Word32();
add(negativePre1, one, negative);
add(a, negative, result);
}
// Adder first clears the result (in cases where the Word32 was used for previous calculations), it then iterates from
// 31 - 0 and adds either 0 or 1 (carrying in cases of 1 + 1) and dropping the carried 1 to the next result set to 0.
public static void add(Word32 a, Word32 b, Word32 result) {
clearWord(result);
int i = 31;
boolean carry = false;
// Iterate 31-0
while(i >= 0) {
// If xor a and b is true, set result to 1 (carry or no carry)
Bit aBit = new Bit(false);
Bit bBit = new Bit(false);
Bit resBit = new Bit(false);
a.getBitN(i, aBit);
b.getBitN(i, bBit);
aBit.xor(bBit, resBit);
// If false, then either a: set a new bit at result[i] to true if both bits are true and there's a carry waiting to be made
// b: If both bits are true and there's no carry, then set it to false and set carry to true
// If both bools are false but there's a carry, then set the num to true and set carry to false.
if(resBit.getValue() == Bit.boolValues.FALSE){
if(aBit.getValue() == Bit.boolValues.TRUE && carry)
result.setBitN(i, new Bit(true));
else if(aBit.getValue() == Bit.boolValues.TRUE && !carry){
result.setBitN(i, new Bit(false));
carry = true;
}
else if(aBit.getValue() == Bit.boolValues.FALSE && carry){
result.setBitN(i, new Bit(true));
carry = false;
}
}
// If Both bits are different, then run this section of code. It only imagines two scenarios:
// a: If there's a carry, then set the bit false (1 + 0 + 1 turns into 1 + 1 (no carry) which is then 0)
// b: If there's no carry present, then simply set it to true.
else{
if(carry)
result.setBitN(i, new Bit(false));
else
result.setBitN(i, new Bit(true));
}
i--;
}
}
// clearWord sets all the bits to false in the input.
public static void clearWord(Word32 input){
for(int i = 0; i < 32; i++){
input.setBitN(i, new Bit(false));
}
}
}