Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
273 views
in Technique[技术] by (71.8m points)

primitive types - Overflowing Short in java

I have one question about the short data type in Java. I know that the range for short is between -32768 to 32767.

So, if I tried to add two short values that exceed the range, the result ends up being the supposed total minus either the positive range or the negative range times 2, as the following:

short a = 30000;
a = (short) (a+a);

the result is -5536.

So the math is 32768 + 32768 = 65536, 6000 - 65536 = -5536.

I know what it does, but I don't know why it does it this way.

Can anybody explain the logic or why Java is doing it this way?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

What's happening is that your number is wrapping around. More specifically, you've got a number 30,000, which in binary is:

0111 0101 0011 0000

When you add it to itself, and carry the 1's, you get:

1110 1010 0110 0000

(Note: it's very easy to multiply a number by 2 in binary -- just shift all the bits one to the left.)

A short is a signed number using two's complement, meaning that that leftmost 1 is really a minus sign; that number represents -5536.

If you multiplied that number by 2 again, you'd need more than 2 bytes to represent it. Since you don't have more than 2 bytes in a short, the extra bits would just get dropped when the int result of the expression is narrowed to a short. Do that enough, and you'll have a 0 as the leftmost digit; the number is positive again. And then eventually you'll have a 1 again as the leftmost; the number is negative again. Eventually you'll have shifted all 0s into the number; multiplying any integer by 2 enough times will always result in 0 (specifically, if it's an N-bit number, multiplying it by 2 N times will always result in 0).

If you weren't narrowing to a short, you'd still eventually run out of digits in the int (when you need 33 or more bits) -- this would result in the extra digits being dropped, which is integer overflow. The same thing would happen if either argument were a long, though it would take 65+ bits.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...