# What is the 2s complement in C?

In C, the two’s complement representation is commonly used to represent signed integers. To obtain the two’s complement of a number, you can follow these steps:

2. If the number is positive (i.e., its most significant bit is 0), then its two’s complement is the same as its binary representation.
3. If the number is negative (i.e., its most significant bit is 1), you need to perform the following steps: a. Invert all the bits (change 1s to 0s and 0s to 1s). b. Add 1 to the inverted result.

Here’s an example to illustrate the process:

Let’s say we want to find the two’s complement of -7.

2. Invert all the bits: 11111000
3. Add 1 to the inverted result: 11111001

So, the two’s complement representation of -7 in C is 11111001.

In C programming, when you declare a signed integer variable and assign a negative value to it, the compiler automatically represents that value using two’s complement notation.

### 2s complement in C example:

Certainly! Let’s take an example to find the two’s complement of a negative number in C.

```#include <stdio.h>

int main() {
int num = -10;
int two_s_complement;

two_s_complement = ~num + 1;

printf("Number: %d\n", num);
printf("Two's complement: %d\n", two_s_complement);

return 0;
}
```

In this example, we have a variable `num` initialized with the value -10. We want to find the two’s complement of this number.

The two’s complement is obtained by performing the following steps:

1. Invert all the bits of the number (`~num`).
2. Add 1 to the inverted result (`~num + 1`).

The resulting two’s complement is then stored in the variable `two_s_complement`.

When we run this program, the output will be:

```Number: -10
Two's complement: 10
```

Therefore, the two’s complement of -10 in C is 10.

Categories C