I hope someone is able to help me.
I have the following algorithm that works both if I have two positive numbers or a positive and a negative number. It doesn’t works, however, if both numbers are negative.
Can someone explain me how is it possible?
void sum (int p, int q) {
int sum, carry;
carry = 1;
while (carry > 0) {
sum = p ^ q;
carry = p & q;
carry = carry << 1;
p = sum;
q = carry;
}
p = p << 1;
p = p >> 1;
printf("The result equals to %d", p);
}
Thanks in advance to everyone 🙂
The sum of two negative numbers is negative (unless an overflow occurs, as pointed out in a comment). But this code:
is essentially clearing the topmost bit, i.e. the sign bit, so the result of this will never be negative.