def SignExtend(val, nbits):
    """ Returns a sign-extended value for the input value.

    val   - value to be sign-extended
    nbits - number precision: 8 - byte, 16 - word etc.
    """
    sign_bit = 1 << (nbits - 1)
    return (val & (sign_bit - 1)) - (val & sign_bit)