Integer Overflow

Integer Overflow - byte c = (byte) test;//should be 128

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

View Full Document Right Arrow Icon
INTEGER OVERFLOW WILLIS FALLS
Background image of page 1

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

View Full DocumentRight Arrow Icon
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
Background image of page 2
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
Background image of page 3

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

View Full DocumentRight Arrow Icon
OVERFLOW DUE TO DOWNCASTING int test = 128; //0x80
Background image of page 4
Background image of page 5
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(&quot;byte c should be %d but is %d%n&quot;,test, c); if(c == -128) System.out.println(&quot;error&quot;); 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 LeBlancs SafeInt class (C++)...
View Full Document

Page1 / 5

Integer Overflow - byte c = (byte) test;//should be 128

This preview shows document pages 1 - 5. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online