Java Reference
In-Depth Information
toHexString(packed));
// Now unpack the letters and output them
long mask = 0xFFFF;
// Rightmost 16 bits as 1
char letter = (char)(packed & mask);
// Extract the rightmost
letter
System.out.println("From right to left the letters in packed
are:");
System.out.println(" " + letter + " 0x" + toHexString(letter));
packed >>= 16;
// Shift out the rightmost
letter
letter = (char)(packed & mask);
// Extract the new
rightmost letter
System.out.println(" " + letter + " 0x" + toHexString(letter));
packed >>= 16;
// Shift out the rightmost
letter
letter = (char)(packed & mask);
// Extract the new
rightmost letter
System.out.println(" " + letter + " 0x" + toHexString(letter));
packed >>= 16;
// Shift out the rightmost
letter
letter = (char)(packed & mask);
// Extract the new
rightmost letter
System.out.println(" " + letter + " 0x" + toHexString(letter));
}
}
The output from this example is the following:
packed now contains 0x44004300420041
From right to left the letters in packed are:
A 0x41
B 0x42
C 0x43
D 0x44
How It Works
The first four statements in main() define variables initialized with the letters to be packed into the vari-
able, packed , of type long that is defined in the fifth statement in main() . The packing process begins
by storing the first character in packed :
packed = letterD; // Store D
The rightmost 16 bits in packed now contain the character code D . This eventually ends up in the leftmost
16 bits of packed . The next statement inserts the next letter, C , into packed:
packed = (packed << 16) | letterC; // Shift and add the next
letter - C
Search WWH ::




Custom Search