java - Why does this multiplication integer overflow result in zero? -


after answering this question, confused why overflowing integer in code resulted in 0 instead of negative number. it's strange, why such exact number? why 0?

public class integeroverflow {   public static void main(string[] args) {     int x = 10;      int = 0;     (i = 0; <= 5; i++)     {       x = x * x;       system.out.println(x);     }   } } 

output:

100 10000 100000000 1874919424 0 0 

this happen if starting value of x even.

according jls §15.17.1:

if integer multiplication overflows, result the low-order bits of mathematical product represented in sufficiently large two's-complement format. result, if overflow occurs, sign of result may not same sign of mathematical product of 2 operand values.

this made more obvious if print numbers in binary format instead of in decimal:

public class integeroverflow {   public static void main(string[] args) {     int x = 10;      int = 0;     (i = 0; <= 5; i++)     {       x *= x;       system.out.println(integer.tobinarystring(x));     }   } } 

output:

1100100 10011100010000 101111101011110000100000000 1101111110000010000000000000000 0 0 

as can see, each time square, double number of 0 bits. since low order bits saved, doubling zeroes every time result in zero. notice do not see these trailing zeroes if starting value x odd. result, instead, result in seemingly unrelated numbers overflow does.

public class integeroverflow {   public static void main(string[] args) {     int x = 11;      int = 0;     (i = 0; <= 5; i++)     {       x *= x;       system.out.format("%-12d\t%s%n", x, integer.tobinarystring(x));     }   } } 

output:

121             1111001 14641           11100100110001 214358881       1100110001101101101101100001 772479681       101110000010110001101011000001 -1419655807     10101011011000011100010110000001 -1709061375     10011010001000011100101100000001 

Comments

Popular posts from this blog

dns - How To Use Custom Nameserver On Free Cloudflare? -

python - Pygame screen.blit not working -

c# - Web API response xml language -