How are integers cast to bytes in Java?

This is called a narrowing primitive conversion. According to the spec:

A narrowing conversion of a signed integer to an integral type T simply discards all but the n lowest order bits, where n is the number of bits used to represent type T. In addition to a possible loss of information about the magnitude of the numeric value, this may cause the sign of the resulting value to differ from the sign of the input value.

So it’s the second option you listed (directly copying the last 8 bits).

I am unsure from your question whether or not you are aware of how signed integral values are represented, so just to be safe I’ll point out that the byte value 1111 1111 is equal to -1 in the two’s complement system (which Java uses).

Leave a Comment