Is this a full adder implementation right?

There is this post that recently got a wonderful group upvotes asking about a + 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; } 

By the way, I also wrote an implementation (exercise with an algorithm) myself and came up with the following:

 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. The fact is that this is much faster than an implementation with a link to a message, without any transitions to x86.

Is my implementation correct or is something wrong that I do not know?
I cannot imagine that my code was faster than the message code, which was frequently viewed and viewed.

+6
source share
1 answer

Your function does not work.

A simple counterexample is 127 + 1.

It is easy to see. The number 127 has everything so that there are no significant 7 bit sets in 1. And with its number 1 and shifting it to the left, we get the value 2. From now on, using the xor operator, no combination of the values ​​available to us can generate a value exceeding 127.

+6
source

All Articles