Search code examples
javacastingintshort

Please explain conversion from int to short


Can anyone please explain to me:

    short s = 0;
    int x = 07;
    int y = 06;
    int z = 123456;

    s= (short) z;
    System.out.println(""+s);

    System.out.println(" "+x+y+s);

Output is

-7616
76-7616

Please explain.


Solution

  • 123456 in hex is 1E240.

    Since a short only has room for two bytes, you lose that first hex digit and end up with E240.

    E240 in binary is 1110001001000000, hence it is a two's-complement negative number. To find the (absolute) value of the negative number represented by that, you invert the digits and add 1.

    0001110110111111 is 7615, add 1 and you get 7616.

    That is why you are seeing -7616.

    More about two's complement here: http://www.cs.cornell.edu/~tomf/notes/cps104/twoscomp.html