Bitwise Operators
Bitwise operators work directly on the binary representation of integers. While less common in high-level business logic, they are crucial for cryptography, network protocols, and optimizing performance.
Bitwise Operations
These operators perform operations on each individual bit of the operands.
| Operator | Name | Description | Example (A=5, B=3) |
|---|---|---|---|
& |
Bitwise AND | 1 if both bits are 1 | 5 & 3 = 1 (0101 & 0011 = 0001) |
| |
Bitwise OR | 1 if at least one bit is 1 | 5 | 3 = 7 (0101 | 0011 = 0111) |
^ |
Bitwise XOR | 1 if bits are different | 5 ^ 3 = 6 (0101 ^ 0011 = 0110) |
~ |
Bitwise Compliment | Inverts all bits (0s become 1s) | ~5 = -6 (conceptually) |
Output
Click Run to execute your code
Bit Shift Operators
Shift operators move the bits of a number to the left or right.
| Operator | Name | Description |
|---|---|---|
<< |
Left Shift | Shifts bits left, filling with 0s. (Multiplies by 2) |
>> |
Signed Right Shift | Shifts bits right, preserving the sign bit. (Divides by 2) |
>>> |
Unsigned Right Shift | Shifts bits right, filling with 0s (ignoring sign). |
Performance Tip: Shifting left by 1 (
x << 1) is
equivalent to multiplying by 2. Shifting right by 1 (x >> 1) is
equivalent to integer division by 2. This was used historically for performance,
but modern compilers optimize standard multiplication/division just as well.
Summary
- Bitwise operators evaluate numbers at the binary level.
&,|,^work similarly to logical operators but on bits.<<shifts bits left (multiply by 2^n).>>shifts bits right (divide by 2^n), preserving sign.- Use
Integer.toBinaryString()to inspect binary values in code.
Enjoying these tutorials?