Tags

A simple java program to make us think.

System.out.println(Long.toHexString(0x100000000L  + 0xcafebabe));

Try it first!

we expect the output to be 1cafebabe. but its quite interesting that we get

cafebabe

as output.

The hexadecimal number 0xcafebabe is considered as a negative number -889275714

its binary equivalent is 11001010111111101011101010111110. The 32nd bit is set and considered as negative.

so try adding decimal numbers (decimal equivalent) 0xcafebabe (-889275714) and 0x100000000 (4294967296) then convert it to hexadecimal. result is 3405691582 i.e 0xcafebabe

As you can see in the code 0xcafebabe has no suffix added to it, so it is considered to be an Integer primitive. In the expression 0x100000000 is a long primitive. This beckons for a Numerical Promotion (widening) of 0xcafebabe from integer to long.

This is where the magic happens, the now converted ‘cafebabe’ in binary has the following representation:

 1111111111111111111111111111111111001010111111101011101010111110

You can verify this by using the “Long.toBinaryString() ” method with the said converted number.

The negative sign bit has been carried to the remaining bit positions of the widened type. Now it simply a matter of adding two 64-bit numbers.

1111111111111111111111111111111111001010111111101011101010111110
0000000000000000000000000000000100000000000000000000000000000000
                                11001010111111101011101010111110
(alt. in Hexadecimal)                                   CAFEBABE

More on CAFEBABE:

 

 

If debugging is the process of removing software bugs, then programming must be the process of putting them in.  – Edsger Dijkstra

Advertisements