def set_bit(v, index, x):
    """
    Set the index:th bit of v to x, and return the new value.
    Note that bit numbers (index) are from 0, with 0 being the least significant bit.
    """
    mask = 1 << index
    v &= ~mask
    if x:
        v |= mask
    return v