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!

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s