Java Reference
In-Depth Information
Figure 2-5 shows how you can use the shift operations to extract either the left or the right 16 bits from
the variable value . You can see here why you have an extra shift right operation that propagates the leftmost
bit. It is related to the notion of a shift as multiplying or dividing by a power of 2, and the implications of
that in the context of negative integers that are represented in 2's complement form (see Appendix B). When
the sign bit is not propagated, the shift right operation does not have a numerical interpretation for negative
values because the sign bit is treated the same as any other bit, and zeros are inserted from the right. When
the sign bit is propagated, the effect for negative values is the same as for positive values — namely that
each bit position shifted is a division by 2.
TRY IT OUT: Using Shift Operations
This example uses the shift operators with the bitwise operators to pack four values of type char into a
variable of type long . Here's the code:
import static java.lang.Long.toHexString;
public class PackingCharacters {
public static void main(String[] args) {
char letterA = 'A';
char letterB = 'B';
char letterC = 'C';
char letterD = 'D';
long packed = 0L;
packed = letterD;
// Store D
packed = (packed << 16) | letterC;
// Shift and add the next
letter - C
packed = (packed << 16) | letterB;
// Shift and add the next
letter - B
packed = (packed << 16) | letterA;
// Shift and add the next
letter - A
System.out.println("packed now contains 0x" +
Search WWH ::




Custom Search