def build_bitfield(left, right, num):
    """ Builds a bit-field in the specified range [left:right]
        with the value 'num', inside a 32-bit integer, and
        returns it.
        
        For example:
            field(4, 2, 3) 
                => 12
        
        Assumptions:
        *   31 >= left >= right >= 0
        *   The number is assumed to be small enough to fit
            the field. If it isn't, its lowest left-right+1 
            bits are taken.
            
        Note that if you take the low bits as the field (N-1:0) 
        and the number is signed, the result will be correct as
        long as the signed number fits in N bits.
    """
    mask = 2 ** (left - right + 1) - 1
    return (int(num) & mask) << right