这两天在研究一个问题时,偶然的越到了 int 越界的问题,我很惊奇的发现,当一个 数 大于了 Integer.MAX_VALUE 时,用 System.out.println() 输出后,会得到一个负数。我很好奇这个负数是怎么来的,所以查了一下资料,了解了一下 Java 对于 int 越界的处理。在 Java 里,
对于 int 的越界处理十分的简单:当一个数超过了 Integer.MAX_VALUE 后,Java 就会从 Integer 的另一头从新开始,也就是从 Integer.MIN_VALUE 往回倒推。也就是 越界数能显示的结果 = Integer.MIN_VALUE + (越界数 – Integer.MAX_VALUE) – 1
代码示例如下:
public static void main(String[] args) {
BigDecimal magic = BigDecimal.valueOf(Math.pow(2, 32)).divide(new BigDecimal(“1.618”), 0, BigDecimal.ROUND_HALF_UP);
System.out.println(magic.intValue() + ” : “ + Integer.toBinaryString(magic.intValue()));
BigInteger bigInteger = new BigInteger(magic.toEngineeringString());
System.out.println(” ” + magic.toEngineeringString() + ” : “+ Long.toBinaryString(bigInteger.longValue()));
System.out.println(Integer.MIN_VALUE+ (magic.longValue() – Integer.MAX_VALUE) – 1);
}
// 结果
-1640475766 : 10011110001110000101001110001010
2654491530 : 10011110001110000101001110001010 -1640475766
参考资料
1.[How doeHow does Java handle integer underflows and overflows and how would you check for it?s Java handle integer underflows and overflows and how would you check for it?]
2.[Integer overflow]
Cialis Se Vende Con Receta https://agenericcialise.com/ – Cialis Kamagra Impacto comprare cialis online Cialis 40 Mg Online
Propecia Vademecum Wicmymmele https://ascialis.com/# – viagra and cialis online gaideleplete Viagra Cialis Levitra Preisvergleich affextop cialis tablets for sale adoreakder Green Tea And Amoxicillin
Amoxicillin For Rabbits obegreeRof https://bbuycialisss.com/# – when will cialis go generic Altele Want to buy isotretinoin us free shipping PafGrade Cialis UnsoneeLetty No Prescription Diflucan
Sexual Side Effects Amoxicillin attactzoob https://agencialisto.com/ – overnight cialis delivery farsef Propecia He Infertilidad skemnils buy cialis online no prescription Hypoge levitra ou cialis homme
Propecia Preis Apotheke Wicmymmele https://asocialiser.com/ – Cialis gaideleplete Propecia United Kingdom affextop Cialis adoreakder Viagra Vs Kamagra
Eolica Al Propecia Wicmymmele https://cialisse.com/ – cialis order online gaideleplete Order Cialis Online In Us affextop Cialis adoreakder Generique Amoxicillin Distribuer Ces
Cialis Generika Wo Kaufen Wicmymmele https://cialiser.com/ – Cialis gaideleplete Cialis Tabs Sale affextop Cialis adoreakder brand cialis vs generic cialis
Propecia Naturale Wicmymmele buying cialis online safely gaideleplete Vente De Clomid Prix
http://hcialischeapc.com/ – canadian pharmacy cialis 20mg
viagra
That is a good tip particularly to those fresh
to the blogosphere. Short but very precise information… Many thanks for sharing this
one. A must read post!
Really no matter if someone doesn’t know after that its up
to other viewers that they will assist, so here it happens.