Bitwise Operators

created:

updated:

tags: bitwise operators algorithms

Bitwise Operators

Bitwise operators are operators that enable us to manipulate individual bits of data or information. Most of bitwise operators are binary, meaning they need a left operand and a right operand. The only unary operator is ~.

AND (&)

  • Performs logical conjunction
  • Only when both left and right operands are 1, the result of the bitwise AND is 1.
  • If left or right operand is 0, the result of the bitwise AND is 0.
  • If both left and right operands are 0, the result of the bitwise AND is 0.

OR (|)

  • Performs logical disjunction
  • If at least one of left or right operands are 1, the result of the bitwise OR is 0.

XOR (^)

  • Performs exclusive disjunction on the bit pairs
  • a XOR b is (a and not b) or (not a and b)
  • It evaluates two mutually exclusive conditions
  • ex: a person can be either a minor or an adult, but not both at the same time
  • Produces 1 only when every bit pair contains opposing bit values
  • (a ^ b) = (a + b) mod 2

NOT (~)

  • Expects one argument (unary bitwise operator)
  • Performs logical negation on a given number by flipping all of its bits
  • ~(1000) is 0111

Left Shift («)

  • Moves the bits of its first operand to the left by the number of places specified in its second operand
  • Fills the gap that arises on the right edge of the new bit pattern.
  • 1101 << 2 is 110100
  • Shifting a single bit to the left by one place doubles its value. It corresponds to multiplying the number by a power of two.
  • a << n is a x 2^n
  • Left shift is used to be a popular optimization technique because bit shifting is a single instruction and cheaper than exponent or product.
  • If working with a single byte, shifting to the left discards all the bits that go beyond its left boundary.
    • 10011 << 2 is 01100

Right Shift (»)

  • Pushes bits to the right by the specified number of places and the rightmost bits always get dropped.
  • By shifting a bit to the right by one position, the value gets halved.
  • 1001101 >> 2 is 0010011
  • a >> n is floor(a / (2^n))

Reference

Bitwise Operators in Python