Is the two's complement of a negative integer used only for addition and subtraction?

410 Views Asked by At

So for example,

13 in binary is: 00000000 00000000 00000000 00001101. Would -13 be stored as 10000000 00000000 00000000 00001101 (using the most significant bit to represent the sign) or would it be stored using the two's complement? (Specifically in C)

If it is stored using the most significant bit to represent the sign, when is two's complement actually used?

2

There are 2 best solutions below

0
On

C may store negative number in any format depending on the implementation. The most popular (nowadays other systems are almost not in use) is two compliment format.

But your numbers are not 2compliment ones.

-13 in binary is 0b11111111111111111111111111110011

to see the unsigned representation of the negative numbers: https://godbolt.org/z/ajDDvc

0
On

Two's compliment is a popular form of representing numbers where half of the binary range is negative. It can be used for all arithmetic operations, not just addition and subtraction. Simply put, it "makes sense" to store numbers this way. A reason against it may be compression algorithms where you want to avoid using too many bits (e.g. zig-zag format and such).

For example, to multiply two 8-bit numbers, "5" and "-3", which are represented in binary as 101 and 11111101, the computer may break this down into a problem of checking each bit in one factor, and adding up the other factor shifted by each bit set:

  5<<0
+ 5<<2 (skipping 5<<1, because that bit is not set)
+ 5<<3
+ 5<<4
+ 5<<5
+ 5<<6
+ 5<<7
------
  1265 

1265 wraps to 241 in an 8-bit space, which is binary 11110001, which is two's complement for -15. On some older computers, multiplication took longer with how many bits of a number are set, likely due to the extra arithmetic required.

Division gets a bit more tricky and is the most expensive arithmetic operation, but the essence here is that two's compliments is a way to store numbers that is easy for computers to work with, as there is no extra logic required to test the sign bit before doing most operations.

In other words, "no", it is not only used for addition and subtraction.