Search code examples
javabytetype-conversionshort

On converting a Short to a Byte what goes on?


I'm new to Java, from PHP, so spending some time/effort understanding types. Then I came across this:

    Byte bb = new Byte("127");
        System.out.println(bb.byteValue());

    Short ss = new Short("32727");
        System.out.println(ss.shortValue());
        System.out.println(ss.byteValue());

Outputs 127, 32727 and -41 ?

Can someone explain to me how it arrived at -41 when the Short 32727 is represented as a byte?


Solution

  • The binary representation of 32727 is 0111111111010111. The byteValue() of that is just the smallest 8 bits, so 11010111

    11010111 is negative since it begins with a 1.

    Taking the Two's complement (complement each bit and then add one) gives 101001 which is 2^5 + 2^3 + 2^0 = 32+8+1 = 41

    So we have -41.