There are four bit operations in Java: the unary negation (~) and the binary and (&), or (|
), and exclusive or (^
), often called xor.
Tables 1 and 2 show the truth tables for the bit operations in Java. When a bit operation is applied to integer values, the operation is carried out on corresponding bits.
For example, suppose we want to compute 46 & 13
. First convert both values to binary. 46decimal = 101110binary (actually 00000000000000000000000000101110 as a 32-bit integer), and 13decimal = 1101binary. Now combine corresponding bits:
The answer is 1100binary = 12decimal.
You sometimes see the |
operator being used to combine two bit patterns. For example, Font.BOLD
is the value 1, Font.ITALIC
is 2. The binary or combination Font.BOLD | Font.ITALIC
has both the bold and the italic bit set:
Don't confuse the &
and |
bit operators with the &&
and ||
operators. The latter work only on boolean
values, not on bits of numbers.
Besides the operations that work on individual bits, there are three shift operations that take the bit pattern of a number and shift it to the left or right by a given number of positions. There are three shift operations: shift left (<<
), right shift with sign extension (>>
), and right shift with zero extension (>>>
).
The left shift moves all bits to the left, filling in zeroes in the least significant bits. Shifting to the left by n bits yields the same result as multiplication by 2n. The right shift with sign extension moves all bits to the right, propagating the sign bit. Therefore, the result is the same as integer division by 2n, both for positive and negative values. Finally, the right shift with zero extension moves all bits to the right, filling in zeroes in the most significant bits. (See Figure 1.)
Note that the right-hand-side value of the shift operators is reduced modulo 32 (for int
values) or 64 (for long
values) to determine the actual number of bits to shift.
For example, 1 << 35
is the same as 1 << 3
. Actually shifting 1 by 35 bits to the left would make no sense—the result would be 0.
The expression
1 << n
yields a bit pattern in which the n
th bit is set (where the 0 bit is the least significant bit).
To set the n
th bit of a number, carry out the operation
x = x | 1 << n
To check whether the n
th bit is set, execute the test
if ((x & 1 << n) != 0) ...
Note that the parentheses around the &
are required—the &
operator has a lower precedence than the relational operators.
3.149.253.210