>
I have the next problem and I haven't found the reason...
I have the next Java code:
int a = -2147483648;
int b = 2147483647;
System.out.println(a - b);
The output of this lines is "1", but I don't understand why.
>
First subtract the numbers in decimal:
-2147483648 - 2147483647 = -4294967295
If you convert that result to hexadecimal as a 'long' you get
-4294967295 = FFFFFFFF00000001x
But Java uses 'int' by default and an 'int' is 32 bits (4 bytes). The low-order 4 bytes of that result are '00000001x' which is '1'.
If you do the math yourself using only 32 bits and use the HEX representation for those numbers it will make more sense.
int a = -2147483648 = 80000000x
int b = 2147483647 = 7FFFFFFFx
Just subtract the numbers like you normally would starting at the right.
1. Substract 'F' from '0' - oops! You need to borrow '1' from the digit to the left which is '0'. You wind up borrowing one from the '8' and getting 10x. Subtract 0Fx from 10x and you get '1' for the right-most digit.
2. Now the second digit from the right is F on the bottom and F on the top (we borrowed one) - subtract and you get 0
3. The 80000000x became 7FFFFFF + 10x when we first borrowed and the '7FFFFFF' is the same as the bottom so all other digits are 0.
If you look at two similar numbers in decimal and do the subtraction it may be easier to see:
a = 5000
b = 4999 (in decimal '9' is the largest 'digit', in hexadecimal 'F' is the largest digit)
What do you get if you subtract those two numbers? You get '1' because when you try to subtract the rightmost '9' from the '0' you have to borrows one from the digit to the left which means borrowing one from the '5' essentially giving the top number as '499' + '10'. Subtract 9 from the 10 giving 1. Then the top has '499' remaining and so does the bottom so the rest are zeroes: 0001.