I am working on the second chapter of Herbert Schildt's C++ beginners's guide. To be honest, I am not very clear what the bit width is and what the corresponding range stands for.
There is one example program code from the book that I completely lost. In particular, 60000 is outside the range of unsigned short int, but the book says that it is within the limit. Furthermore, where does -5536 come from?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
#include <iostream>
/* This program shows the difference between
signed and unsigned integers;*/
usingnamespace std;
int main(){
shortint i;// a signed short integer
shortunsignedint j;
// an unsigned short integer
j=60000;
i=j;
cout<<i<<" "<<j;
return 0;
}
If objects of type short int occupy 2 bytes then their range of values is
-32768 : 32767.
unsigned short uses the sign bit as a value bit. So it can hold in two times more values: 0 : 65535.
Usually computers uses two-complement arithmetic such a way that for any number x
x + ( -x ) == 0
For example if x = 1 ( 0001 ) then -x can be get by reversing all bits and adding 1. So -1 will be represented as FFFE + 1 = FFFF
In this case
0001
+
FFFF
==
0000
In your example j = 60000. It is less than the maximum for unsigned short that is equal to as I pointed 65535. And it is a negative value because 60000 is greater than the maximum for signed short that is equal to 32767.
To determine what is it equal to in decimal notation we should subtract 65535 - 60000 + 1. That is equal to 5536. So it is negative number -5536.
short int goes up to a maximum of +32767. When you set this equal to 60000, it will first of all fill up the maximum size it can hold on the positive side. Then it wraps around to the extreme range it can hold and works it's way up until it wraps back around again or finally stops at a value that it can hold.
In this case 60000 is assigned to i.
i = 60000;
i = 32767 <---maximum positive
i = -32768 <---wraps around to smallest negative
Remainder to add is now 27232
i += 27232
i = -5536 <---Finally settles on this number because it can hold it now
vald from moscow,
What does F and E here represent?
Smac89,
You have a different approach from the "vald from moscow", I am not sure how you work it out particularly at the last two lines:
i += 27232
i = -5536 <---Finally settles on this number because it can hold it now