Java Reference
In-Depth Information
10.14 Bit handling
Yo umay occasionally need to access and manipulate data at the bit level. For
example, each bit in a set of data might represent the on/off state of a sensor or a
pixel in a detector array. Representing the values as bits is much more memory
efficient than assigning a full byte to each detector element if each element can
be only in one of two states.
A more common application of bitwise operations deals with colors. We saw
in Chapter 6 that in Java the RGB & alpha components (red, green, blue, and
the transparency factor) for a color pixel are each assigned a byte value and the
four bytes are packed in an int field. For image processing (see Chapter 11)
and other graphics applications, you can use the bitwise operators to obtain these
bytes from a color value, modify the component values, and then pack them back
into an int value.
10.14.1 Bitwise operations
In Appendix 2 we display a table of the bitwise operators that act on the individual
bits in integer type values. Four of the operators carry out Boolean operations on
the bits. The ~ x compliment operation flips each bit in x. The x&y , x | y ,
and x ^ y operations perform AND, OR, and XOR, respectively, between the
corresponding bits in the x and y values. For the case where a bitwise operator
involves two operands of different integer types, the wider type results.
The other three bit operators involve shifting of bits. The shift left operation,
x << y , shifts x to the left by y bits. The high-order bits are lost while zeros fill
the right bits. The signed shift right operation, x >> y , shifts x to the right by y
bits. The low-order bits are lost while the sign bit value (0 for positive numbers,
1 for negative) fills in the left bits. The unsigned shift right, operation, x >>>
y , shifts x to the right by y bits. The low-order bits are lost while zeros fill in the
left bits regardless of the sign.
The following code shows how to place the four color component values into
an int variable. We use the hexadecimal format for the literal constants as a
compact way to specify byte values.
int[] aRGB ={0x56, 0x78, 0x9A, 0xBC};
int color - val = aRGB[3];
color val = color - val | (aRGB[2] << 8);
color - val = color - val | (aRGB[1] << 16);
color - val = color - val | (aRBG[0] << 24);
This results in color - val holding the value: 56 78 9A BC (separating the byte
values for clarity). Similarly, to obtain a particular byte from an int value, the
code goes like:
Search WWH ::




Custom Search