def swap_bits(x, i, j):
  """
  Swap the ith and jth indices in 'x'.
  """
  # Extract the i and j indices to see if they differ.
  if (x >> i) & 1 != (x >> j) & 1:
    # Retrieve the bits to flip by shifting to
    # the ith and jth indices. Create a bit mask.
    bit_mask = (1 << i) | (1 << j)
    # Flip bits. 
    #   x ^ 1 = 0 when x = 1. 
    #   x ^ 1 = 0 when x = 0.
    x ^= bit_mask
  return x