Puzzle (The Joy of Hex)
Consider the following example.
package demo;
public class App {
public static void main( String[] args ) {
System.out.println( Long.toHexString( 0x100000000L + 0xcafebabe ) );
}
}
The above seems to be adding the following two Hexadecimal numbers
100000000
cafebabe
This output represents the low-order 32 bits of the correct sum, but somehow the thirty-third bit gets lost.
cafebabe
This example was taken from PUZZLE 5: THE JOY OF HEX in Java™ Puzzlers: Traps, Pitfalls, and Corner Cases.
“Decimal literals have a nice property that is not shared by hexadecimal or octal literals: Decimal literals are all positive JLS 3.10.1. To write a negative decimal constant, you use the unary negation operator (-
) in combination with a decimal literal. In this way, you can write any int
or long
value, whether positive or negative, in decimal form, and negative decimal constants are clearly identifiable by the presence of a minus sign. Not so for hexadecimal and octal literals. They can take on both positive and negative values. Hex and octal literals are negative if their high-order bit is set. In this program, the number 0xcafebabe
is an int
constant with its high-order bit set, so it is negative. It is equivalent to the decimal value -889275714
.”
“The addition performed by the program is a mixed-type computation: The left operand is of type long
, and the right operand is of type int
. To perform the computation, Java promotes the int
value to a long
with a widening primitive conversion JLS 5.1.2 and adds the two long
values. Because int
is a signed integral type, the conversion performs sign extension: It promotes the negative int
value to a numerically equal long
value.”