19.5. Signed and Unsigned Integral Types

[ fromfile: twoscomplement.xml id: twoscomplement ]

This section explains the differences between signed and unsigned integral types.

The underlying binary representation of an object x of any integral type looks like this (assuming n-bit storage):

dn-1dn-2...d2d1d0
   

where each di is either 0 or 1. The computation of the decimal equivalent value of x depends on whether x is an unsigned or signed type. If x is unsigned, the decimal equivalent value is

     dn-1*2n-1 + dn-2*2n-2 +...+ d2*22 + d1*21 + d0*20
   

The largest (positive) value that can be expressed by an unsigned integer is, therefore,

2n - 1 = 1*2n-1 + 1*2n-2 +...+ 1*22 + 1*21 + 1*20
   

If x is signed, the decimal equivalent value is

     dn-1*-(2n-1) + dn-2*2n-2 +...+ d2*22 + d1*21 + d0*20
   

The largest (positive) value that can be expressed by a signed integer is

2n-1 - 1 = 0*-(2n-1) + 1*2n-2 +...+ 1*22 + 1*21 + 1*20
   

This is called "two's complement" representation. To determine the representation of the negative of a signed integer,

  1. Compute the "one's complement" of the number (i.e., replace each bit with its complement).

  2. Add 1 to the "one's complement" produced in the first step.

8-bit Integer Example

Suppose that you have a tiny system that uses only 8 bits to represent a number. On this system, the largest unsigned integer would be

11111111 = 128 + 64 + 32 + 16 + 8 + 4 + 2 + 1 = 255

But that same number, interpreted as a signed integer, would be

11111111 = -128 + 64 + 32 + 16 + 8 + 4 + 2 + 1 = -1