I am working on implementing an 8-bit adder abstracted with code in Java. This 8-bit adder is built from 8 full adder circuits. For those who don't know what a full adder is, it's a circuit that computes the sum of 2 bits.
My intention was to use a for loop to add each corresponding bit of the adders 2, 8-bit inputs, such that a new bit of the 8-bit result is computed each time the for loop iterates.
Would it be possible to store the new computed bit of each iteration in a variable holding the 8-bit result using bit shifting?
Here's an example to help explain what I am asking. The bold bit would be the one that is shifted into the int holding the result.
0b00001010
+
0b00001011
Initial State
Sum: 0
Result: 0b00000000
Carry: 0
First Iteration (addition starting w/ LSB)
Sum: 1
Result: 0b0000000 1
Carry: 0
Second Iteration
Sum: 0
Result: 0b000000 0 1
Carry: 1
Third Iteration
Sum: 1
Result: 0b00000 1 01
Carry: 0
Fourth Iteration
Sum: 0
Result: 0b0000 0 101
Carry: 1
Fifth Iteration
Sum: 1
Result: 0b000 1 0101
Carry: 0
Sixth, Seventh, Eigth Iteration
Sum: 0, 0, 0 respectively
Result: 0b 000 10101
Carry: 0, 0, 0 respectively
Since you are starting the computation at the least significant bit end and progress toward the most significant bit end as you go, you need an operation to place a bit in n
-th position, as opposed to shifting in a bit * .
Placing n
-th bit in an initially zeroed value is simple - you shift 1
left by n
, and then OR the shifted value with the result, like this:
int value = 0;
int n = 3;
int valueWithNthBitSet = value | (1 << n);
At this point, valueWithNthBitSet
is equal to b00000100
.
You can apply this trick repeatedly to place the results that you get from your full adders into the bits of the result:
int res = 0;
int a = 10;
int b = 11;
int carry = 0;
for (int bit = 0 ; i != 8 ; i++) {
int aBit = getBit(a, i);
int bBit = getBit(a, i);
int resBit = fullAdderGetResultBit(aBit, bBit, carry);
carry = fullAdderGetCarryBit(aBit, bBit, carry);
if (resBit == 1) {
res |= 1 << i;
}
}
When the loop is over, the result would be equal to the two values added together.
* Shifting in would apply if you started at the MSB and progressed toward LSB as you go.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.