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.