O'Reilly logo

Ivor Horton's Beginning Java™ 2, JDK™ 5th Edition by Ivor Horton

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

2.10. Bitwise Operations

As you already know, all these integer variables we have been talking about are represented internally as binary numbers. A value of type int consists of 32 binary digits, known to us computer fans as bits. You can operate on the bits that make up integer values using the bitwise operators, of which there are four available:

&AND
|OR
^Exclusive OR
~Complement

Each of these operators operates on the individual bits in its operands as follows:

  • The bitwise AND operator, &, combines corresponding bits in its two operands such that if the first bit AND the second bit are 1, the result is 1—otherwise, the result is 0.

  • The bitwise OR operator, |, combines corresponding bits such that if either or both bits are 1, then the result is 1. Only if both bits are 0 is the result 0.

  • The bitwise exclusive OR (XOR) operator, ^, combines corresponding bits such that if both bits are the same the result is 0; otherwise, the result is 1.

  • The complement operator, ~, takes a single operand in which it inverts all the bits, so that each 1 bit becomes 0, and each 0 bit becomes 1.

You can see the effect of these operators in the examples shown in Figure 2-5.

Figure 2.5. Figure 2-5

Figure 2-5 shows the binary digits that make up the operands and the results. Each of the three binary operations applies to each corresponding pair of bits from its operands in turn. The complement operator ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required