-2147483648 can be but 2147483648 can't

i tried to print random no in java language





In 1st ss the no is in range of int , its fine output
In 2nd ss the no is out of range of int ,its fine output.
In 4th ss its in the range of long so its fine output.
but whats the bug in the 3rd ss ?

its beyond the range of int, as range of int is from -2147483648 to 2147483647 therefore when you try printing 2147483648 it is out of the range. In the third case you tried to convert long into int, which is a lossy compression, that was the error.

You have to know how numbers are stored internally. An int is a 32 bit datatype, where the 32nd bit is used for the sign.

The binary representation of 2147483648 is 10000000 00000000 00000000 00000000. To store this number, you have to meddle with the leading bit, who’s sole purpose is for just identifying the sign of the number. Hence, the maximum positive value you can store is 01111111 11111111 11111111 11111111 which is 2147483647, because positive values have the leading bit as 0.

Negative values are stored as the 2’s complement of the corresponding positive value, and hence negative numbers will have the leading bit as 1. You are able to store a negative max of -2147483648, because:
2147483648 is 10000000 0000000 0000000 0000000
who’s 1’s complement is 01111111 11111111 11111111 11111111
and 2’s complement is 10000000 00000000 00000000 00000000
(Yes, 2’s complement is equal to the actual number, which is why we cannot store the positive value and the negative value, because of ambiguity).

Note: The 2’s complement turns out to be the same because we’re only looking at 32 bits. We we take 33 bits for instance:

+2147483648: 0 10000000 0000000 0000000 0000000
-2147483648: 1 10000000 0000000 0000000 0000000

As there is no 33rd bit for int, there is ambiguity, and we cannot store both +2147483648 and -2147483648.

If you are using unsigned int, you can store a max value of 4294967295 11111111 11111111 11111111 11111111

4 Likes

Ya
just one thing!
2’s complelement of positive no are same as the sign magnitude form
2,s complement of negative no are same as the sign magnitude form as you stated above but its only in special case when no is 2 to power something .