Future Billionaire - 11 months ago 67

C Question

The question is

What are two's complement numbers of the following 16-bit numbers?

1.0x3f9d

My answer is 0011111110011101 in binary because 0x3f9d is a positive number. However, some people said that the answer is 1100000001100011. I am confusing because 1100000001100011 is a negative number. Which one is the right answer?

Answer Source

3F9Dh is a positive number, equal to 0011 1111 1001 1101 binary. It only makes sense to speak of two's complement when a number is negative.

You might be confusing the term two's complement presentation (of a number) with the algorithm "calculate two's complement of x". If you would calculate the two's complement of 3F9Dh, you would indeed end up with 1100 0000 0110 0011.

In C you could do this calculation as

```
(uint16_t)~0x3F9D + 1
```

which is equivalent to

```
(uint16_t)-0x3F9D
```

(assuming two's complement CPU and not some exotic nonsense CPU)