UTHM2012
UTHM2012

Reputation: 91

Adding two integers without using plus operator

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?

Upvotes: 2

Views: 1000

Answers (5)

kapilddit
kapilddit

Reputation: 1769

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


Upvotes: 0

nullptr
nullptr

Reputation: 11058

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.

Upvotes: 3

user529758
user529758

Reputation:

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.

Upvotes: 1

Tom Tanner
Tom Tanner

Reputation: 9354

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.

Upvotes: 0

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 727047

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;

Upvotes: 6

Related Questions