/* * T01n02.java -- Demonstrates twos-complement integer overflow. We start * with a large integer value, and increase it by one until doing so * causes the sign bit to flip, making the result very negative. */ import java.io.*; public class T01n02 { final static int BITS_PER_INT = 32; // Java ints always have 32 bits public static void main (String[] args) { int intValue = 2147483645; // 2^31 - 3 bitPrint(intValue); System.out.println(" = " + intValue++); bitPrint(intValue); System.out.println(" = " + intValue++); bitPrint(intValue); System.out.println(" = " + intValue++); bitPrint(intValue); System.out.println(" = " + intValue++); } /* * bitPrint(value) -- Displays an int in twos-complement binary form. * This method uses very little that we've covered in class to this * point, so don't worry about how it works! */ public static void bitPrint (int value) { int mask = 1 << (BITS_PER_INT-1); for (int i=1; i <= BITS_PER_INT; i++) { System.out.print(((value & mask) == 0) ? "0" : "1"); value <<= 1; } } }