Cloudbook: C

  1. Home
  2. Variables
  3. Numbers
  4. § 3 exercise →
Numbers

Signed types represent both positive and negative numbers, assigning half of the representations to each sign. There are several representations that can be used. We shall consider the representation called two's complement.

For a value represented by x, let x' be a representation obtained by "flipping all bits of x". A two byte short is 16 bits, or 4 hexidecimal bits. For instance, 0xaaaa is the bit patterns of alternating 1's and 0's starting with a 1 in the most significant bit. x' is called the complement of x.

If we represent the value 0 by all zeros, then 0' is all ones. Note that 0'+1=0, therefore 0'=-1.

A negative number is defined by the equation x+(-x)=0. Note that x+x'=0'=-1; therefore x+(x'+1)=0 or -x = x'+1.

If x and -x are distinct, we can pair those values in our representation. Considering now 0, for which -0 is identically 0, we have accounted for an odd number of representations:

        0, -1, 1, -2, 2, ...
        
Since there are an even number of representations to be accounted for, by counting argument there must be another number for which x and -x are not distinct; i.e. a second solution to the "signed arithmetic of finite size" equation x=-x. The representation of this number is almost "negative zero", as it is the representation of 0 except that the most significant bit is made one.

We assign this as a negative number so that was have the simple rule: "in two's complement, numbers with MSB zero are positive, numbers with MSB 1 are negative".

Counting from 0 we then have the infinitely repeating circular sequence:

        0, 1, 2, ..., 2k-1-1, -2k-1, ..., -1, 0, ...
        

There are two numerical jumps in the sequence caused by overflow in the addition of one: the numerically small jump between -1 and 0; and the numerically large jump between 2k-1-1 and -2k-1.