Java Reference
In-Depth Information
< Day Day Up >
Puzzle 5: The Joy of Hex
The following program adds two hexadecimal, or "hex," literals and prints the result in hex. What
does the program print?
public class JoyOfHex {
public static void main(String[] args) {
System.out.println(
Long.toHexString(0x100000000L + 0xcafebabe));
}
}
Solution 5: The Joy of Hex
It seems obvious that the program should print 1cafebabe . After all, that is the sum of the hex
numbers 100000000 16 and cafebabe 16 . The program uses long arithmetic, which permits 16 hex
digits, so arithmetic overflow is not an issue. Yet, if you ran the program, you found that it prints
cafebabe , with no leading 1 digit. This output represents the low-order 32 bits of the correct sum,
but somehow the thirty-third bit gets lost. It is as if the program were doing int arithmetic instead
 
 
Search WWH ::




Custom Search