how come the answer is showing negative value for an unsigned integer.
Signed and unsigned integers
hello @Jaideep_singh
pls refer this ->
First of all let’s understand, what exactly is an unsigned number.
For that, we first need to understand, what is a signed number. As the name suggests, we can store both positive and negative numbers.
Sounds simple, but how is this done in Computers. Computers understand only language consisting of 0s & 1s.
So, if I really want my memory variable to be able to store both 5 & -5, I can’t store both of them as 101 which is binary representation of 5. I want my computer to understand that when I say if a number is positive or negative. Seems like we will require, a bit to represent that sign on the number.
Exactly.
In computer languages, Most significant bit is reserved for the sign on the number in signed variables. But, just these negative number’s are stored as 2’s complement for ease & speed of computation.
But, since, we are using up a bit to store sign, we have a bit less to store value of the number. Because of this, capacity of signed variables is half their counter-part i.e. Unsigned integers. (Only in value terms)
With this explanation, we can now easily understand what is unsigned integer.
So, as the name suggests, we don’t have any bit reserved to store the sign of the number. So, we can store only positive numbers.
OK. We can assign negative numbers.
So, let’s assign -5 to unsigned integer and see what happens.
For simplicity of calculations, let’s assume our integer to be of size 2 byte or 16-bits.
So, -5 would be stored as 1111111111111011. First, digit 1, represents negative number as explained above. But, since this is unsigned integer, this would reflect as 65531.
In this case, since we know that we have assigned -5 to the variable. But, since this is an unsigned integer, Computer has no way to determine that first digit was the signed bit. Now, just imagine a case where we actually assign 65531 to this integer. Even this would be stored as 1111111111111011. So, now imagine how can computer determine whether we originally assigned negative number or a positive one.
And that’s precisely why we have signed and unsigned variables.
So, the answer to the question is that though, we can assign negative number to an unsigned number but it would come out as positive only.
I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.
On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.