Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is this full adder implementation correct?

Tags:

c

algorithm

add

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.

like image 258
cadaniluk Avatar asked Feb 29 '16 13:02

cadaniluk


People also ask

Will you implement a full adder from half adder explain properly?

Full Adder using Half AdderA Full Adder can also be implemented using two half adders and one OR gate.

Which is correct for full adder?

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.

What are the different types of adder implementation?

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.


1 Answers

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. Anding 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.

like image 74
2501 Avatar answered Oct 13 '22 12:10

2501