Thread: range of unsigned integer

1. range of unsigned integer

Hello friends,

I am following a book that states that range of unsigned integers is from 0 to 65535 for 16-bit compilers but this simple program has perplexed me:

Code:
```main()
{
unsigned i, j;
clrscr();
i = 32768;
j = 32767;
printf("%d      %d",i,j);
getch();
}```
The output given by this program is -32768 32767.
Why is it going to the negative side when the range is from 0 to 65535;
I am using Borland C++ version 3.1 in Windows XP.
Thanks a lot.

2. printf doesnt know the type of value you pass ( how should it, you can pass any type you want ).
It trusts on the format spacifiers that you pass in the format string.
You passed %d that stands for a signed integer.
Kurt

3. First of all, using a 16-bit compiler on a 32-bit OS at the present time is pretty dumb. You'll learn a bunch of stuff that is already outdated currently, but will be less and less useful as 64-bit systems are being rolled out.

Secondly, signed and unsigned is really more of a concept. You're not making the variable itself signed or unsigned. You're giving a hint to the compiler how to actually treat math operations and such. Consider binary representation for a second.

If I gave the 16-bit number 0xFFFF, what number is it? The signed representation could be -1 while the unsigned representation could be 65535. printf() doesn't have the luxury of knowing what type of number you're giving it because it's a variadic function. It acts on the arguments it receives based upon what is in the first argument. This is why you're using things like %d. %d tells printf() to treat a variable as if it's an integer. The issue is that printf() will treat the value matching %d as if it's signed.

Hint: Try %u.

Popular pages Recent additions