def shift_with_sign(val, bits, shift):
    """shift value extending sign in twocs format"""
    if val < 0:
        assert len(bin(val)) - 3 <= bits
    else:
        assert len(bin(val)) - 2 <= bits
    ormask = int('1' * shift + '0' * (bits - shift), 2)
    mask = int('1' * bits, 2)
    return (val >> shift | ormask) & mask
