Java Reference
In-Depth Information
Figure C.2 shows how the bitwise operators are used to pack information
into a 16-bit integer. Such information is maintained by a typical university
for a wide variety of reasons, including state and federal mandates. Many of
the items require simple yes/no answers and are thus logically representable
by a single bit. As Figure C.2 shows, 10 bits are used to represent 10 catego-
ries. A faculty member can have one of four possible ranks (assistant, associ-
ate, and full professor, as well as nontenure earning), and thus two bits are
required. The remaining 4 bits are used to represent one of 16 possible col-
leges in the university.
Lines 24 and 25 show how tim is represented. Tim is a tenured associate
professor in the College of Arts and Science. He holds a Ph.D., is a U.S. citi-
zen, and works on the university's main campus. He is not a member of a
minority group, disabled, or a veteran. He is on a 12-month contract. Thus
tim 's bit pattern is given by
0011 10 1 0 1 1 1 1 0 0 0 0
or 0x3af0 . This bit pattern is formed by applying the OR operator on the
appropriate fields.
Lines 28 and 29 show the logic used when Tim is deservedly promoted to
the rank of full professor. The RANK category has the two rank bits set to 1 and
all other bits set to 0; or
0000 11 0 0 0 0 0 0 0 0 0 0
The complement, ~RANK , is thus
1111 00 1 1 1 1 1 1 1 1 1 1
Applying a bitwise AND of this pattern and tim 's current setting turns off
tim 's rank bits, giving
0011 00 1 0 1 1 1 1 0 0 0 0
The result of the bitwise OR operator at line 29 thus makes tim a full profes-
sor without altering any other bits, yielding
0011 11 1 0 1 1 1 1 0 0 0 0
We learn that Tim is tenured because tim&TENURED is a nonzero result. We
can also find out that Tim is in College #3 by shifting to the right 12 bits and
then looking at the resulting low 4 bits. Note that parentheses are required.
The expression is (tim>>12)&0xf .
Search WWH ::




Custom Search