Java Reference
In-Depth Information
You need to be careful when shifting
byte
and
short
values because Java will automat-
ically promote these types to
int
when evaluating an expression. For example, if you right
shift a
byte
value, it will first be promoted to
int
and then shifted. The result of the shift
will also be of type
int
. Often this conversion is of no consequence. However, if you shift
a negative
byte
or
short
value, it will be sign-extended when it is promoted to
int
. Thus,
the high-order bits of the resulting integer value will be filled with ones. This is fine when
performing a normal right shift. But when you perform a zero-fill right shift, there are 24
ones to be shifted before the byte value begins to see zeros.
Bitwise Shorthand Assignments
All of the binary bitwise operators have a shorthand form that combines an assignment
with the bitwise operation. For example, the following two statements both assign to
x
the
outcome of an XOR of
x
with the value 127.
Ask the Expert