def compact_from_target(target):
    """\
    The “compact” format is a representation of a whole number N using an
    unsigned 32bit number similar to a floating point format. Conversion
    necessarily involves truncation if the target is greater than 2^23-1.

    The most significant 8 bits are the unsigned exponent of base 256.
    This exponent can be thought of as "number of bytes of N".
    The lower 23 bits are the mantissa.
    Bit number 24 (0x800000) represents the sign of N.
    N = (-1^sign) * mantissa * 256^(exponent-3)

    Satoshi's original implementation used BN_bn2mpi() and BN_mpi2bn().
    MPI uses the most significant bit of the first byte as sign.
    Thus 0x1234560000 is compact (0x05123456)
    and  0xc0de000000 is compact (0x0600c0de)
    (0x05c0de00) would be -0x40de000000

    Bitcoin only uses this “compact” format for encoding difficulty
    targets in the block header, which are unsigned 256bit quantities.
    Thus, all the complexities of the sign bit and using base 256 are
    probably an implementation accident.

    This implementation directly uses shifts instead of going
    through an intermediate MPI representation."""
    bn = _BigInteger(target).serialize()
    size = len(bn)
    if size <= 3:
        word = target << 8 * (3 - size)
    else:
        word = target >> 8 * (size - 3)
    if word & 0x00800000:
        word >>= 8
        size += 1
    word |= size << 24
    if target < 0:
        word |= 0x00800000
    return word
\
    The “compact” format is a representation of a whole number N using an
    unsigned 32bit number similar to a floating point format. Conversion
    necessarily involves truncation if the target is greater than 2^23-1.

    The most significant 8 bits are the unsigned exponent of base 256.
    This exponent can be thought of as "number of bytes of N".
    The lower 23 bits are the mantissa.
    Bit number 24 (0x800000) represents the sign of N.
    N = (-1^sign) * mantissa * 256^(exponent-3)

    Satoshi's original implementation used BN_bn2mpi() and BN_mpi2bn().
    MPI uses the most significant bit of the first byte as sign.
    Thus 0x1234560000 is compact (0x05123456)
    and  0xc0de000000 is compact (0x0600c0de)
    (0x05c0de00) would be -0x40de000000

    Bitcoin only uses this “compact” format for encoding difficulty
    targets in the block header, which are unsigned 256bit quantities.
    Thus, all the complexities of the sign bit and using base 256 are
    probably an implementation accident.

    This implementation directly uses shifts instead of going
    through an intermediate MPI representation.