Why the range of int is -32768 to 32767?

Because of how numbers are stored. Signed numbers are stored using something called “two’s complement notation”.

Remember all variables have a certain amount of bits. If the most significant one of them, the one on the left, is a 0, then the number is non-negative (i.e., positive or zero), and the rest of the bits simply represent the value.

However, if the leftmost bit is a 1, then the number is negative. The real value of the number can be obtained by subtracting 2^n from the whole number represented (as an unsigned quantity, including the leftmost 1), where n is the amount of bits the variable has.

Since only n – 1 bits are left for the actual value (the “mantissa”) of the number, the possible combinations are 2^(n – 1). For positive/zero numbers, this is easy: they go from 0, to 2^(n – 1) – 1. That -1 is to account for zero itself — for instance, if you only had four possible combinations, those combinations would represent 0, 1, 2, and 3 (notice how there’s four numbers): it goes from 0 to 4 – 1.

For negative numbers, remember the leftmost bit is 1, so the whole number represented goes between 2^(n – 1) and (2^n) – 1 (parentheses are very important there!). However, as I said, you have to take 2^n away to get the real value of the number. 2^(n – 1) – 2^n is -(2^(n – 1)), and ((2^n) – 1) – 2^n is -1. Therefore, the negative numbers’ range is -(2^(n – 1)) to -1.

Put all that together and you get -2^(n – 1) to 2^(n – 1) – 1. As you can see, the upper bound gets a -1 that the lower bound doesn’t.

And that’s why there’s one more negative number than positive.

Leave a Comment