Reputation: 1040
I'm checking the Java doc, and seeing that Integer.MIN_VALUE is -2^31:
A constant holding the minimum value an int can have, -2^31.
While in C++, the 32 bits signed integer "long" has a different MIN value:
LONG_MIN: Minimum value for an object of type long int -2147483647 (-2^31+1) or less*
I am very confused why they are different and how Java get -2^31? In Java, if an integer has 32 bits and the first bit is used for sign, -2^31+1 is more logical, isn't it?
Upvotes: 1
Views: 901
Reputation: 490398
C and C++ are intended to work with the native representation on machines using 1s or 2s complement or signed magnitude. With 2s complement you get a range from -2 n through 2 n -1, about like in Java. Otherwise you lose the most negative number and gain a representation for -0.
In C++ you're only guaranteed that n
(the number of bits)is at least 16 where Java guarantees it's exactly 32.
Upvotes: 1
Reputation: 3819
The value of the most significant bit in a 32 bit number is 2^31, and as this is negative in a signed integer the value is -2^31. I guess C++ uses -2^31+1 as the MIN_VALUE because this means it has the same absolute value as MAX_VALUE i.e. 2^31-1. This means an integer could store -MIN_VALUE, which is not the case in Java (which can cause some fun bugs).
Upvotes: 2