Following code
BigInteger number=new BigInteger("2154789654785210095153123254756845");
boolean b=number.longValue()>Long.MIN_VALUE;
boolean c=number.longValue()<Long.MAX_VALUE;
boolean d=number.longValue()>=Integer.MIN_VALUE;
boolean e=number.longValue()<=Integer.MAX_VALUE;
System.out.println(""+b);
System.out.println(""+c);
System.out.println(""+d);
System.out.println(""+e);
generates output
true
true
false
true
Keeping in mind that after achieving MAX_VALUE
in Integer,value goes back to MIN_VALUE
and loops again, if a value is <=Integer.MAX_VALUE
, then it must be >=Integer.MIN_VALUE
, then why does boolean variable d
returns false
?
This can be explained once we understand what longValue()
is returning.
Converts this BigInteger to a long. This conversion is analogous to a narrowing primitive conversion from long to int as defined in section 5.1.3 of The Java™ Language Specification: if this BigInteger is too big to fit in a long, only the low-order 64 bits are returned. Note that this conversion can lose information about the overall magnitude of the BigInteger value as well as return a result with the opposite sign.
Printing the value of this variable yields -4694333933485660691
, a value that is certainly a legal long
value but is far less than Integer.MIN_VALUE
(which is implicitly converted to a long
here), so false
is correct for the d
printout.
Both the b
and c
outputs are true
because the value -4694333933485660691
is greater than Long.MIN_VALUE
, and because the value -4694333933485660691
is less than Long.MAX_VALUE
. The only values that would print false
for b
and c
are those BigInteger
s that would convert to Long.MIN_VALUE
AND Long.MAX_VALUE
themselves, respectively, when longValue()
is called.
It can be easily understood by printing values as below
number.longValue()[-4694333933485660691]>Long.MIN_VALUE[-9223372036854775808 = true
number.longValue()[-4694333933485660691]<Long.MAX_VALUE[9223372036854775807 = true
number.longValue()[-4694333933485660691]>=Integer.MIN_VALUE[-9223372036854775808 = false
number.longValue()[-4694333933485660691]<=Integer.MAX_VALUE[9223372036854775807 = true
Hope this helps
从Java 1.8开始,您可以使用BigInteger.longValueExact()
,如果BigInteger值无法精确表示为long值,则会抛出ArithmeticException
。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.