def signExtend(x, n=8):
    """
    Returns signed integer that is the sign extention of n bit unsigned integer x
    in twos complement form where x has n significant bits

    This is useful when unpacking bit fields where the bit fields use two's complement
    to represent signed numbers. Assumes the the upper bits (above n) of x are zeros
    Works for both positive and negative x
    """
    m = 1 << (n-1)  # mask
    r = (x ^ m) - m
    return (r)