Hi All, I'm working thru RHE & on p39 there's a discussion on integers overflowing. I can see what the codes doing but when I try to work it by hand I get the wrong answer. Although the text says don't worry about the detail, I am interested in the detail. The code looks like this: int a = 12345, b= 234567, c c = a * b / b s.o.p(c) results in -5965. OK my questions are: 1) does a * b get evaluated first? Is Left to Right always the case with evaluation? 2) a * b results in 2895729615. Which I know is larger than the integer range but how does Java arrive at -1399237681. I know this is tedious detail but I'm just getting a bit hung up by it. Regards Paul
Hi Paul, 1) When you have same precedence, the evaluation will be left to right. * and / are in same precedence. 2) 2895729615 = 10101100100110010101001111001111 in binary. Note that Most Significant Bit has 1 means it is negative. Bala.
1) does a * b get evaluated first? Is Left to Right always the case with evaluation? Order of evaluation is described in detail in the JLS (�15.7) For multiplication division, yes, it is from left to right.
2) a * b results in 2895729615. Which I know is larger than the integer range but how does Java arrive at -1399237681. If you are running under Windows, pull up the Calculator and set the view to Scientific. Select the "Dec" radio button, then type in 2895729615. Now select the "Bin" radio button. You will see the binary equivalent, which is (spaces added for readability): 1010 1100 1001 1001 0101 0011 1100 1111 The leftmost bit is the sign bit. 0 in the sign bit indicates a positive number, 1 indicates a negative number. That makes the binary representation above a negative number. To find out what the magnitude of that number is, you need to calculate its two's complement: To get the two's complement of 1010 1100 1001 1001 0101 0011 1100 1111 invert all the bits (if you still have Calculator up, click on the "Not" button) 0101 0011 0110 0110 1010 1100 0011 0000 then add 1, which will give you 0101 0011 0110 0110 1010 1100 0011 0001 Now, select the "Dec" radio button and you should see 1399237681 That is the magnitude of the negative number represented by the original: 1010 1100 1001 1001 0101 0011 1100 1111
[This message has been edited by JUNILU LACAR (edited June 21, 2001).]