It seems like the question was asked to make you ask them:
- What is the largest value that you want the
integer
type to encode?
Let's assume they said we want MAX_VALUE
to be the maximum value an integer type can have.
This brings us to the equation. Since we are encoding it using bits we need log_2(MAX_VALUE)
bits to encode any positive value of size up to MAX_VALUE
. The logarithm of base 2 is there because with a bit pattern of size n
you can encode up to 2^n
different values. So if you want to know how long your maximum bit pattern needs to be to encode MAX_VALUE
you need to calculate the log
since:
2^(log_2(MAX_VALUE)) = MAX_VALUE
Now this is okay, unless you also want to encode the number 0. If you want to encode 0 as well then there are MAX_VALUE+1 numbers between 0 and MAX_VALUE so you need log_2(MAX_VALUE+1)
bits to encode them all.
Another important question is what is the MIN_VALUE
that we want to encode?
So in total you have MAX_VALUE + 1 + abs(MIN_VALUE)
different values, so you will need :
bits_needed = log_2(MAX_VALUE + 1 + abs(MIN_VALUE))
As others have mentioned, in java int
has max_value = 2,147,483,647
and min_value = -2,147,483,648
. When you do the calculation you get log_2(4294967296)
which is equal to 32. So 32 bits is the size of the integer type in java.