The following code:
public class Example005 {public static void main (string[] args) {System.out.println ("out1=" + long.tohexstring ( 0x100000000l + 0xcafebabe)); System.out.println ("out2=" + long.tohexstring (0x100000000l + 0xcafebabeL));}}
Output Result:
Out1=cafebabeout2=1cafebabe
Cause Analysis:
One of the first things to know is that the decimal number is represented by a leading unary operator (+/-). hexadecimal, octal, and binary are used in the computer as a complement. The advantage of the complement is that the symbol and other bits can be processed uniformly using the complement, and subtraction can be handled by addition. In addition, if the highest bit (sign bit) has a carry, the carry is discarded when the number of two complements is added. In the above program, the number 0xcafebabe is an int constant, its highest bit is set, so it is a negative. It is equal to the decimal value-889275714.
This addition performed by OUT1 is a mixed-type calculation (Mixed-type computation): The left operand is a long type, and the right operand is of type int. To perform this calculation, Java promotes the numeric value of type int to a long type with the widening primitive type conversion, and then adds the two long values. Because int is a signed integer type, this transformation performs a conforming extension: it promotes the numeric value of the negative int to a long value equal to the number. The right operand of this addition 0xcafebabe is promoted to the value 0xffffffffcafebabeL of the long type. This number is then added to the left operand 0x100000000l. When viewed as an int type, the high 32 bits of the right operand after the symbol extension are-1, and the high 32 bits of the left operand are 1, and the two values are added to 0, which explains why the leading 1 in the OUT1 is lost.
In Out2,0xcafebabeL uses hexadecimal literal Changlianglai to avoid damaging symbol extensions, so the printing results are correct.
This article from "Winger" blog, declined reprint!
"Java Doubts" hex addition problem