{[ promptMessage ]}

Bookmark it

{[ promptMessage ]}

Integer Overflow

# Integer Overflow - byte c =(byte test/should be 128...

This preview shows pages 1–5. Sign up to view the full content.

INTEGER OVERFLOW WILLIS FALLS

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document
OVERFLOW EXAMPLE byte b = 120; //0x78 for(int i = 0; i < 140; i++) System. out.println(b++); Where b = 0x80, b becomes negative 120 121 122 123 124 125 126 127 -128 -127 -126 -125 -124 -123 -122 -9 -8 -7 -6 -5 -4 -3 -2 -1 0 1 2 3
OVERFLOW DUE TO DOWNCASTING int test = 1200; byte a = (byte)test; //0x4B0 System.out.printf("byte a = %d or %s in hex%n", a, Integer.toHexString(a)); Byte takes the low order bits from the integer therefore a = 0xB0 Code Output: (f is just sign extension) byte a = -80 or ffffffb0 in hex

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document
OVERFLOW DUE TO DOWNCASTING int test = 128; //0x80
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: byte c = (byte) test;//should be 128 System.out.printf("byte c should be %d but is %d%n",test, c); if(c == -128) System.out.println("error"); The 8-th bit is the sign bit for bytes. Code Output: byte c should be 128 but is -128 error AVOIDING OVERFLOW • Use unsigned types when possible • Check inputs and outputs • I.e. Adding two positives should not result in negative • Make tests as simple as possible, do not try to be clever • Set limits on method parameters • Use David LeBlanc’s SafeInt class (C++)...
View Full Document

{[ snackBarMessage ]}