Bit manipulation is a powerful technique used to solve problems by directly manipulating bits. Here are some common bit manipulation techniques:
- AND Operation (
&
):
- Used to clear bits.
- Example: To check if the least significant bit (LSB) is set:
java if (x & 1) { // LSB is set }
- OR Operation (
|
):
- Used to set bits.
- Example: To set the 3rd bit of a number to 1:
java x = x | (1 << 3);
- XOR Operation (
^
):
- Used to flip bits.
- Example: To toggle the 3rd bit:
java x = x ^ (1 << 3);
- NOT Operation (
~
):
- Flips all the bits of a number.
- Example:
java x = ~x; // All bits are flipped
- Left Shift (
<<
):
- Shifts bits to the left, essentially multiplying the number by powers of 2.
- Example:
java x = x << 2; // Equivalent to multiplying x by 4
- Right Shift (
>>
):
- Shifts bits to the right, effectively dividing the number by powers of 2.
- Example:
java x = x >> 2; // Equivalent to dividing x by 4
- Unsigned Right Shift (
>>>
):
- Shifts bits to the right without considering the sign of the number (used for unsigned integers).
- Example:
java x = x >>> 2;
- Checking if a number is a power of 2:
- A number is a power of 2 if it has exactly one bit set to 1.
- Example:
java boolean isPowerOfTwo = (x > 0) && (x & (x - 1)) == 0;
- Counting Set Bits (Hamming Weight):
- To count the number of 1s in the binary representation of a number:
java int count = 0; while (x > 0) { count++; x = x & (x - 1); // This clears the lowest set bit }
Clearing the Lowest Set Bit:
- To clear the lowest set bit (i.e., turn the first 1 bit from the right to 0):
java x = x & (x - 1);
- To clear the lowest set bit (i.e., turn the first 1 bit from the right to 0):
Setting the Lowest Unset Bit:
- To set the lowest 0 bit (turn the first 0 bit from the right to 1):
java x = x | (x + 1);
- To set the lowest 0 bit (turn the first 0 bit from the right to 1):
Extracting a Specific Bit:
- To get the value of the nth bit:
java boolean bit = (x & (1 << n)) != 0;
- To get the value of the nth bit:
These techniques are useful for optimizing certain problems, especially those involving binary arithmetic, number properties, or data representation.