def compact_from_uint256(v):
    """Convert uint256 to compact encoding
    """
    nbytes = v.bit_length() + 7 >> 3
    compact = 0
    if nbytes <= 3:
        compact = (v & 16777215) << 8 * (3 - nbytes)
    else:
        compact = v >> 8 * (nbytes - 3)
        compact = compact & 16777215
    if compact & 8388608:
        compact >>= 8
        nbytes += 1
    return compact | nbytes << 24
