def twos_comp(n, b):
    """Calculates the two's complement of a given number.

    Parameters
    ----------
    n : int
        Number to calculate its two's complement.
    b : int
        Number of bits.

    Examples
    --------
    Given `bits` = 3 and `n` = 4 (0b100), twos_comp(4, 3) equals -4 (0b100).
    Given `bits` = 4 and `n` = 4 (0b0100), twos_comp(4, 4) equals 4 (0b0100).

    Returns
    -------
    int
        Two's complement of `n` with `b` bits.

    """
    if (n & (1 << (b - 1))) != 0:
        n = n - (1 << b)
    return n