manikanta_01's blog

By manikanta_01, history, 31 hour(s) ago, In English

Bit manipulation is a powerful technique used to solve problems by directly manipulating bits. Here are some common bit manipulation techniques:

  1. AND Operation (&):
  • Used to clear bits.
  • Example: To check if the least significant bit (LSB) is set: java if (x & 1) { // LSB is set }
  1. OR Operation (|):
  • Used to set bits.
  • Example: To set the 3rd bit of a number to 1: java x = x | (1 << 3);
  1. XOR Operation (^):
  • Used to flip bits.
  • Example: To toggle the 3rd bit: java x = x ^ (1 << 3);
  1. NOT Operation (~):
  • Flips all the bits of a number.
  • Example: java x = ~x; // All bits are flipped
  1. 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
  1. 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
  1. Unsigned Right Shift (>>>):
  • Shifts bits to the right without considering the sign of the number (used for unsigned integers).
  • Example: java x = x >>> 2;
  1. 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;
  1. 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 }
  1. 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);
  2. 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);
  3. Extracting a Specific Bit:

    • To get the value of the nth bit: java boolean bit = (x & (1 << n)) != 0;

These techniques are useful for optimizing certain problems, especially those involving binary arithmetic, number properties, or data representation.

  • Vote: I like it
  • +2
  • Vote: I do not like it