Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding two integers without using plus operator

Tags:

c

addition

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?

like image 266
UTHM2012 Avatar asked Feb 27 '26 20:02

UTHM2012


2 Answers

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;
like image 67
Sergey Kalinichenko Avatar answered Mar 01 '26 09:03

Sergey Kalinichenko


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.

like image 23
nullptr Avatar answered Mar 01 '26 08:03

nullptr