Search code examples
javacastingintegeroverrun

Casting long to byte in Java


I am unable to understand the following:

In java,

long l = 130L;  
byte b = (byte)l;

If I print the value of b, why do I get -126? What is the bit representation of long l?


Solution

  • Bytes are signed in Java - so the range of values is -128 to 127 inclusive.

    The bit pattern for 130 as a long, when simply truncated to 8 bits, is the bit pattern for -126 as a byte.

    As another example:

    int x = 255;
    byte b = (byte) x; // b is now -1