Java Reference
In-Depth Information
Binary
0110
0110
1100
1101
6
6
12
13
Decimal value
6
6
C
D
Hexadecimal
So the value of the variable a in hexadecimal is 0x66CD , where the 0x prefix indicates that this is a
hexadecimal value. The variable b in the illustration has the hexadecimal value 0x000F . If you think of
the variable b as a mask applied to a , you can view the & operator as keeping bits unchanged where the
mask is 1 and setting the rest to 0. Mask is a term used to refer to a particular configuration of bits
designed to select out specific bits when it is combined with a variable using a bitwise operator. So if
you want to select a particular bit out of an integer variable, just AND it with a mask that has that bit set
to 1 and all the others as 0.
You can also look at what the & operator does from another perspective - it forces a bit to 0, if the
corresponding mask bit is 0. Similarly, the | operator forces a bit to be 1 when the mask bit is 1.
The & and | operators are the most frequently used, mainly for dealing with variables where the
individual bits are used as state indicators of some kind for things that can be either true or false, or on
or off. You could use a single bit as a state indicator determining whether something should be
displayed, with the bit as 1, or not displayed, with the bit as 0. A single bit can be selected using the &
operator - for example, to select the third bit in the int variable indicators , you can write:
thirdBit = indicators & 0x4; // Select the 3rd bit
We can illustrate how this works if we assume the variable indicators contains the hexadecimal
value 0xFF07 :
Hexadecimal
Binary
indicators
0xFF07
1111
1111
0000
0111
0x4
0000
0000
0000
0100
mask value
indicators & 0x4
0x4
0000
0000
0000
0100
All these values should have 32 bits and we are only showing 16 bits here, but you see all you need to
know how it works. The mask value sets all the bits in indicators to zero except for the third bit. Here,
the result of the expression is non-zero because the third bit in indicators is 1.
On the other hand, if the variable indicators contained the value 0xFF09 the result would be different:
Hexadecimal
Binary
indicators
0xFF09
1111
1111
0000
1001
0x4
0000
0000
0000
0100
mask value
indicators & 0x4
0x0004
0000
0000
0000
0000
Search WWH ::




Custom Search