There is this post, which has recently received some remarkable bunch of upvotes, asking about the +
operator in C.
It shows the following implementation:
// replaces the + operator
int add(int x, int y) {
while(x) {
int t = (x & y) <<1;
y ^= x;
x = t;
}
return y;
}
Coincidentally, I wrote an implementation myself too (an algorithm book exercise) and came up with that:
uint32_t bit_add(uint16_t a, uint16_t b) {
uint32_t carry = ((uint32_t) a & b) << 1;
uint16_t add = a ^ b;
return carry ^ add;
}
I tested it a couple of times and it seems to work. Thing is, it is significantly faster than the implementation from the referenced post, lacking any jumps on an x86.
Is my implementation correct or is there something wrong I am not aware of?
I cannot imagine my code to be faster than the code of a post so often seen and reviewed.
Full Adder using Half AdderA Full Adder can also be implemented using two half adders and one OR gate.
Full Adder is the adder that adds three inputs and produces two outputs. The first two inputs are A and B and the third input is an input carry as C-IN. The output carry is designated as C-OUT and the normal output is designated as S which is SUM.
In this section, we have discussed in brief the different architectures of adder, namely, ripple carry adder (RCA), Carry Look-Ahead Adder (CLA), CSA, SQRT-CSA, and Common Boolean Logic (CBL) adder.
Your function doesn't work.
A simple counterexample is 127 + 1.
This is easy to see. Number 127 has all lest significant 7 bits sets to 1. And
ing it with the number 1, and shifting it one to the left, will give the value 2. From then on, using the operator xor
, no combination of values we have available, can produce a value that is larger than 127.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With