2

I found a source code in C language. I take from here :link:

#include<stdio.h>
int main()
{
    int a,b,hasil;
    printf("Masukan integer pertama: ");
    scanf("%d",&a);
    printf("Masukan integer kedua: ");
    scanf("%d",&b);
    hasil = a - ~b -1;
    printf("Hasil tambah kedua-dua integer :%d",hasil);
    return 0;
}

Seem, the code don't use "+" or "- -" operation to add thus two integers. Can anybody tell me, what are this technique or concept be used?

1
  • This relies on the representation of integers being two's complement. That's true of most modern computers but is not required by the standard. Commented Jun 7, 2013 at 16:45

5 Answers 5

6

This "technique" is a brain teaser. As far as the practical use goes, it is about as useless as it gets: all it does is computing negative b in two's complement without using unary minus:

-b == (~b + 1)
a+b == a - (-b) == a - (~b + 1) == a - ~b - 1;
Sign up to request clarification or add additional context in comments.

Comments

3

An addition is replaced with subtraction here: a + b = a - (-b). Since in most current processors (at least in all I am aware of) negative integers are represented as a two's complement, -b = ~b + 1 (bitwise NOT and then plus 1). Hence, a + b = a - (~b + 1) = a - ~b - 1.

1 Comment

Unfortunately this has one broken corner case: b==INT_MIN.
1

This line:

hasil = a - ~b -1;

is the magic. The code assumes that signed integers are represented using 2's complement representation, which is overly popular nowadays. One property of this representation is that if interpreted as unsigned (as a raw bit pattern, how the ~ operator treats it), negative numbers are represented as (1 << bitwidth) - n, where n is the absolute value of the negative number, and bitwidth is the number of bits in an int.

This essentially results in the fact that bitwise NOT-ing a number k transforms it to - k - 1, so a - (~b) - 1 is just a - (-b - 1) - 1 = a + b.

Comments

0

Someone once designed a processor that only implemented the subtract instruction, which was a little more elegant than the referenced code.

The code

c = a - ~b - 1;

is a slightly over complex way of saying

c = a - -b;

and moreover requires 2's complement arithmetic.

Comments

0

Here is the Program:

#include <stdio.h>

#include <conio.h>


unsigned int f (unsigned int a , unsigned int b);


unsigned int f (unsigned int a , unsigned int b)

{

   return a ?   f ( (a&b) << 1, a ^b) : b;

}


int main()

{


int a = 9;

int b = 7;


int c = f(a,b);

printf("Sum = %d", c);

getch();

return 0;


}

Output: Sum = 16


Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.