I'm having a hard time grasping data types in C. I'm going through a C book and one of the challenges asks what the maximum and minimum number a short
can store.
Using sizeof(short);
I can see that a short consumes 2 bytes. That means it's 16 bits, which means two numbers since it takes 8 bits to store the binary representation of a number. For example, 9 would be 00111001
which fills up one bit. So would it not be 0 to 99 for unsigned, and -9 to 9 signed?
I know I'm wrong, but I'm not sure why. It says here the maximum is (-)32,767 for signed, and 65,535 for unsigned.
short int, 2 Bytes, 16 Bits, -32,768 -> +32,767 Range (16kb)
Think in decimal for a second. If you have only 2 digits for a number, that means you can store from 00
to 99
in them. If you have 4 digits, that range becomes 0000
to 9999
.
A binary number is similar to decimal, except the digits can be only 0
and 1
, instead of 0
, 1
, 2
, 3
, ..., 9
.
If you have a number like this:
01011101
This is:
0*128 + 1*64 + 0*32 + 1*16 + 1*8 + 1*4 + 0*2 + 1*1 = 93
So as you can see, you can store bigger values than 9
in one byte. In an unsigned 8-bit number, you can actually store values from 00000000
to 11111111
, which is 255 in decimal.
In a 2-byte number, this range becomes from 00000000 00000000
to 11111111 11111111
which happens to be 65535.
Your statement "it takes 8 bits to store the binary representation of a number" is like saying "it takes 8 digits to store the decimal representation of a number", which is not correct. For example the number 12345678901234567890 has more than 8 digits. In the same way, you cannot fit all numbers in 8 bits, but only 256 of them. That's why you get 2-byte (short
), 4-byte (int
) and 8-byte (long long
) numbers. In truth, if you need even higher range of numbers, you would need to use a library.
As long as negative numbers are concerned, in a 2's-complement computer, they are just a convention to use the higher half of the range as negative values. This means the numbers that have a 1
on the left side are considered negative.
Nevertheless, these numbers are congruent modulo 256 (modulo 2^n
if n
bits) to their positive value as the number really suggests. For example the number 11111111
is 255 if unsigned, and -1
if signed which are congruent modulo 256.