algorithms

2’s Complement – C Program

We can obtain 2’s complement in atleast two ways through a C program.

If n is a number then -n will give the result.

The next approach is to first flip all the bits (1’s complement) and then add 1. The bits can be flipped using ~ operator.

The program below demonstrates both the approaches.

#include 

int main()
{
    int num = 7;

    /// Two ways to get two's complement
    printf("%d\n", -num);
    printf("%d\n", ~num + 1);
    return 0;
}

Let me Know What you Think!