Java Reference
In-Depth Information
The letter is inserted by first shifting the contents of packed left by 16 bits, and then ORing the value of
letterC with the result. At this point, the leftmost 32 bits of packed are zero and the rightmost 32 bits
contain D followed by C .
The next two statements repeat the same process to insert B and then A :
packed = (packed << 16) | letterB; // Shift and add the next
letter - B
packed = (packed << 16) | letterA; // Shift and add the next
letter - A
Now the variable packed holds the codes for all four characters in the sequence D , C , B , and A .
The output produced by the next statement confirms this:
System.out.println("packed now contains 0x" +
This statement uses the toHexString() method defined in the Long class to generate a string containing
a hexadecimal representation of the value of packed . Because you have a static import statement for the
name of this method, you don't need to qualify it with the class name. You can see from the output that
this consists of the character code values 0x44 , 0x43 , 0x42 , and 0x41 , which are the codes for the letters
D through A .
The program then demonstrates how you can use the shift operators combined with the bitwise AND to
extract the four char values from packed . The first step is to define a mask to select the rightmost 16 bits
in a value of type long :
long mask = 0xFFFF; // Rightmost 16 bits as 1
The next statement uses mask to pick out the rightmost character code in packed :
char letter = (char)(packed & mask); // Extract the rightmost
The cast to type char of the value that results from ANDing mask with packed is necessary because the
compiler does not insert an automatic cast from type long to type char .
The next two statements output a heading followed by the first letter as a letter and its code:
System.out.println("From right to left the letters in packed
System.out.println(" " + letter + " 0x" + toHexString(letter));
To get at the next character, you can shift out the character just extracted and AND the result with mask
once again:
packed >>= 16; // Shift out the
rightmost letter
letter = (char)(packed & mask); // Extract the new
rightmost letter
Search WWH ::

Custom Search