In C
programming or any other programming laanguages, there is a term
called range of the data type say “int”. If I talk about the C
programming specifically, the size of an int data type is 2 bytes or
4 bytes depending upon the operating system used. Let’s assume the
size of an int data type is 2 bytes for this moment. What should be
the range of int now?
Well,
if we talk about signed int, then its between -32768 to 32767. It’s
something that we read in a textbook or any other source. How is it
calculated? Let’s find it.
As
we know, 1 Byte = 8 bits. Which means 2 Bytes = 16 bits. So the
Maximum number this data type can store is 216.
Which equals to
65535. Let’s understand
this. We said it’s 16 bits, means we can have two values i.e either
0 or 1 for each bit.
|
0 , 1
|
0 , 1
|
0 , 1
|
0 , 1
|
0 , 1
|
0 , 1
|
0 , 1
|
0 , 1
|
0 , 1
|
0 , 1
|
0 , 1
|
0 , 1
|
0 , 1
|
0 , 1
|
0 , 1
|
0 , 1
|
That
is why the range of an unsigned int lies between 0 – 65535. If we
talk about the signed int range, then it’s -215
to 215
– 1. As we reserve the left most bit for the sign. So we are left
with only 15 bits for storing the values.
So
whenever we need to calculate the range of any integer data type, we
need to get the size of that data type so that we can calculate the
total number of bits. Once the total number of bits is available we
can calculate the range(unsigned) by simply 0 - 2(total
number of bits).
Similarly, the signed range of that data type would be: - 2(total
number of bits – 1) to
2(total number of
bits – 1) -1.
Why
that -1 ?? Well it’s because 0 is treated as positive number. For
example, if we have to divide 10 numbers in to equal parts the
division would be like....
-5 -4 -3 -2 -1 0 1 2 3 4
So
let’s calculate the range of a hypothetical integer data type which
takes 3 Bytes in memory. 3 Bytes means 3 * 8 = 24 bits.
So
the unsigned range will be : 0 – 224
And,
signed range will be
:
- 223
– 223
– 1
Hope
you can calculate the range of integer data type of any size.
No comments:
Post a Comment