0

About (unsigned)

What is the meaning of this statements? int variable1= -5; int take; take=(unsigned)variable1; Can anybody tell me what is the action about (unsigned)?

2nd Oct 2017, 12:34 PM
Yusuf
Yusuf - avatar
6 Answers
+ 1
By default, the range of integers is -(2^31) to (2^31-1). That means any number between this range will be easily stored as int. This int range is called signed, which simply means that it will store + and - numbers. (With sign). Now, sometimes, you deal with only positive numbers. So you may increase the range for your storage. This is done by saving your number to an unsigned int, which will only store positive numbers. Now, your range will become 0 to 2^32-1. Thus. using (unsigned) means casting, or changing the variable's value to the type specified inside brackets.(unsigned in this case). Thus, if negative numbers are stored in unsigned variables, they will automatically become 2^32-(value of negative number). This is done because All integers do the same when their limits are crossed. So your take, will store 2^32-5.
2nd Oct 2017, 12:44 PM
Solo Wanderer 4315
Solo Wanderer 4315 - avatar
+ 2
Yes. Now, you save the 2^32-5 back in a signed int. (Ints are signed by default). So you get -5 again as a result of conversion...
2nd Oct 2017, 1:01 PM
Solo Wanderer 4315
Solo Wanderer 4315 - avatar
+ 1
Wow amazing.
2nd Oct 2017, 1:03 PM
Yusuf
Yusuf - avatar
+ 1
I have one more question. When I print it with %u, it shows me 2^32-5, but when I print it with %d I am getting -5. Why? @Kinshuk Vasisht
2nd Oct 2017, 1:28 PM
Yusuf
Yusuf - avatar
+ 1
%u is a format specifier for unsigned ints. It will convert to unsigned, and then print. %d is for normal numbers (signed).
2nd Oct 2017, 1:33 PM
Solo Wanderer 4315
Solo Wanderer 4315 - avatar
0
But the problem is that when I am running the program with cout<<take;, I am see -5, not 2^32-5. @Kinshuk Vasisht
2nd Oct 2017, 12:58 PM
Yusuf
Yusuf - avatar