img
The reason Java (and most other computer languages) uses two's complement is easy to
see when you consider the issue of zero crossing. Assuming a byte value, zero is represented by
00000000. In one's complement, simply inverting all of the bits creates 11111111, which creates
negative zero. The trouble is that negative zero is invalid in integer math. This problem is solved
by using two's complement to represent negative values. When using two's complement, 1 is
added to the complement, producing 100000000. This produces a 1 bit too far to the left to
fit back into the byte value, resulting in the desired behavior, where ­0 is the same as 0, and
11111111 is the encoding for ­1. Although we used a byte value in the preceding example,
the same basic principle applies to all of Java's integer types.
Because Java uses two's complement to store negative numbers--and because all
integers are signed values in Java--applying the bitwise operators can easily produce
unexpected results. For example, turning on the high-order bit will cause the resulting
value to be interpreted as a negative number, whether this is what you intended or not.
To avoid unpleasant surprises, just remember that the high-order bit determines the sign
of an integer no matter how that high-order bit gets set.
The Bitwise Logical Operators
The bitwise logical operators are &, |, ^, and ~. The following table shows the outcome of
each operation. In the discussion that follows, keep in mind that the bitwise operators are
applied to each individual bit within each operand.
A
B
A|B
A&B
A^B
~A
0
0
0
0
0
1
1
0
1
0
1
0
0
1
1
0
1
1
1
1
1
1
0
0
The Bitwise NOT
Also called the bitwise complement, the unary NOT operator, ~, inverts all of the bits of its
operand. For example, the number 42, which has the following bit pattern:
00101010
becomes
11010101
after the NOT operator is applied.
The Bitwise AND
The AND operator, &, produces a 1 bit if both operands are also 1. A zero is produced in all
other cases. Here is an example:
00101010
42
& 00001111
15
00001010
10
Search WWH :
Custom Search
Previous Page
Java SE 6 Topic Index
Next Page
Java SE 6 Bookmarks
Home