## 2012-07-23

### Addition of two short type numbers causing a negative result

I will try to explain this using a simple example. Following code adds two short type numbers and assign the result to another short type variable.

short num1 = 30000, num2 = 30000;
short answer = (short)num1+num2;

But if you see the result, you will get a negative number.

The value range of short data type is -32,768 to 32,767. So the first line is correct because we are storing 30000 (which is less than 32,767) in the variables.

But in the second line, we are adding those two variables which results in 60000 which is bigger than the maximum value which can be stored for a short variable.

Binary representation of the 60000 is 1110101001100000

Binary representation of the 32,767 is 0111111111111111

The first bit is the sign bit. 0 represent positive number and 1 represent negative number. That's why the Binary representation value of the 32,767 is 0111111111111111 (Notice the leading 0). short data type can store only 15 bits (Except the sign bit). As I said, the first bit is used to indicate the sign (negative or positive) of the number. But the binary value of 60000 (1110101001100000) requires 16 bits. So when we store the 60000 in a short variable the leading 1 will assigned to the sign bit and as a result of it, we are getting a negative number. The leading sign bit has the value of 2^15. When it's positive, it's 0 (Because the value of the bit is 0). But when it's negative, it has the value of -2^15 (-32768).

So let's go back to the result 60000. When we assign the value to a short variable, the binary representation of it 1110101001100000 will assign the leading 1 to the sign bit. So now it has value of -32768. Except the sign bit, the left over is 110101001100000 (Notice that I've left out the leading 1) which's value is 27232. So altogether, when we take that value with the sign bit, the final value is  -32768+27232 =-5536.