binaryBit Manipulation

Notes and typical questions for bits related problems

Notes

  • Binary to Decimal Conversion

    • 110121101_2 =123+022+121+120=1*2^3 + 0*2^2 + 1*2^1 + 1*2^0 =8+0+2+1=11=8+0+2+1=11

  • Java int is 32 bits.

  • Get the last bit of an int number: int bit = n&1

  • Bit operation precedence is kind of low. Protect it with ()

  • XOR (exclusive OR)

    • Rules

      • 0 ^ a = a

      • a ^ a = 0

      • a ^ b ^ c = a ^ c ^ b

    • Use cases

      • Swap 2 var without temp var

        int x = 10, y = 20;
        x = x ^ y;  // x becomes 30 (binary XOR of 10 and 20)
        y = x ^ y;  // y becomes 10 (original value of x)
        x = x ^ y;  // x becomes 20 (original value of y)
      • Find a Single Number in an Array. There are some special requirements on the array.

  • Two's complementary (二进制补码)

    • In Java (and most modern systems), negative numbers are stored in two’s complement format.

      • If n is an integer, -n = ~n+1 . In this way, -n+n will have zero in all bits

    • Also, based on this, n&(-n) is a way to keep the rightmost 1-bit and to set all the other bits to 0.

Typical Questions

Last updated