def set_bits(register: int, value, index, length=1):
    """
    Set selected bits in register and return new value

    :param register: Input register value
    :type register: int
    :param value: Bits to write to register
    :type value: int
    :param index: Start index (from right)
    :type index: int
    :param length: Number of bits (default 1)
    :type length: int
    :return: Output new register value
    :rtype: int
    """
    mask = (1 << length)-1
    register = register & ~(mask << index)
    register = register | (mask & value) << index
    return register