What does "-1" represent in the value range for unsigned int and signed int?

n bits can represent 2n different values. (The first bit can have two values * the second bit can have two values * the third bit can have two values * ...)

For example, 3 bits can form 23 = 8 different bit patterns, and thus up to 8 different values.

000
001
010
011
100
101
110
111

If each bit pattern represents an integer, then an n-bit integer can represent 2n different integers. For example,

  • It could represent the integers from 0 to 2n-1 inclusively
    (because (2n-1) - (0) + 1 = 2n different values).

    For example,

    000   0
    001   1
    010   2
    011   3
    100   4
    101   5
    110   6
    111   7
    
  • It could represent the integers from -2n-1 to 2n-1-1 inclusively
    (because (2n-1-1) - (-2n-1) + 1 = 2n different values).

    For example,

    100  -4
    101  -3
    110  -2
    111  -1
    000   0
    001   1
    010   2
    011   3
    

You could assign any meaning to these values, but the previously stated ranges are the ones understood by twos'-complement machines for unsigned integers and signed integers respectively.[1]


  1. On a ones'-complement machine, there are two ways of writing zero (0000...00002 and 1000...00002), so the range is only -2n-1-1 to 2n-1-1. I think all modern machines are twos'-complement machines, though.

Consider the values you can achieve with 2 bits:

00 : 0
01 : 1
10 : 2
11 : 3

There are 4 of them, 2 to the power of 2.
But the highest value is not 4, it is 3.
The highest value is 2 to the power of 2 minus 1. I.e. in your representation

2^2-1
or 22-1

Add a bit and you get twice the number, by adding

100 : 4
101 : 5
110 : 6
111 : 7

Total number 8, but highest number 7.

So the "-1" is because always the first of the total of 2n is used for 0,
the 2nd is used for 1, the 3rd is used for 2.
In the end (2n)th one is not available for 2n, it is already used for 2n-1.

Tags:

C