def twos_complement(val: int, num_bits: int) -> int:
    """Returns the num_bits-bit two's complement of the input value."""
    mask = 2 ** (num_bits - 1)
    twos_comp = -(val & mask) + (val & ~mask)
    return twos_comp