fileames

Bitwise

Simple Checks

  • Check if even:
(x & 1) == 0
  • Check if power of two:
(x & x-1) == 0

Flip Bit at a Position

def flip(x, pos):
    mask = 1 << position
    return x ^ mask

Is Bit Set?

def is_set(x, pos):
    return (x >> pos) & 1

Modify Bit

def is_set(x, pos, state):
    mask = 1 << position
    return (x & ~mask) | (-state & mask)

Count Set Bits

Resources