System.out.println("
b = 0x"
+ hex[(b >> 4) & 0x0f]
+ hex[b & 0x0f]);
System.out.println("
b >> 4 = 0x"
+ hex[(c >> 4) & 0x0f]
+ hex[c & 0x0f]);
System.out.println("
b >>> 4 = 0x"
+ hex[(d >> 4) & 0x0f]
+ hex[d & 0x0f]);
System.out.println("(b &
0xff) >> 4 = 0x"
+ hex[(e >> 4) & 0x0f]
+ hex[e & 0x0f]);
}
}
The following output of this program shows how the >>> operator appears to do nothing
when dealing with bytes. The variable b is set to an arbitrary negative byte value for this
demonstration. Then c is assigned the byte value of b shifted right by four, which is 0xff
because of the expected sign extension. Then d is assigned the byte value of b unsigned
shifted right by four, which you might have expected to be 0x0f, but is actually 0xff because
of the sign extension that happened when b was promoted to int before the shift. The last
expression sets e to the byte value of b masked to 8 bits using the AND operator, then shifted
right by four, which produces the expected value of 0x0f. Notice that the unsigned shift right
operator was not used for d, since the state of the sign bit after the AND was known.
b
=
0xf1
b >> 4
=
0xff
b >>> 4
=
0xff
(b & 0xff) >> 4
=
0x0f
Bitwise Operator Compound Assignments
All of the binary bitwise operators have a compound form similar to that of the algebraic
operators, which combines the assignment with the bitwise operation. For example, the
following two statements, which shift the value in a right by four bits, are equivalent:
a = a >> 4;
a >>= 4;
Likewise, the following two statements, which result in a being assigned the bitwise
expression a OR b, are equivalent:
a = a | b;
a |= b;
The following program creates a few integer variables and then uses compound bitwise
operator assignments to manipulate the variables:
class OpBitEquals {
public static void main(String args[]) {
int a = 1;
int b = 2;
int c = 3;
a |= 4;
b >>= 1;
Search WWH :
Custom Search
Previous Page
Java SE 6 Topic Index
Next Page
Java SE 6 Bookmarks
Home