Appendix J. Bit and Shift Operations

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.

Table J.1. The Unary Negation Operation

a

~a

0

1

1

0

Table J.2. The Binary And, Or, and Xor Operations

a

b

a & b

a | b

a ^ b

0

0

0

0

0

0

1

0

1

1

1

0

0

1

1

1

1

1

1

0

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 Binary And, Or, and Xor Operations

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:

The Binary And, Or, and Xor Operations

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 ...

Get Big Java, 4th Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.