mpz_t variables can be converted to and from arbitrary words of binary
data with the following functions.
The parameters specify the format of the data. count many words are read, each size bytes. order can be 1 for most significant word first or -1 for least significant first. Within each word endian can be 1 for most significant byte first, -1 for least significant first, or 0 for the native endianness of the host CPU. The most significant nails bits of each word are skipped, this can be 0 to use the full words.
There is no sign taken from the data, rop will simply be a positive integer. An application can handle any sign itself, and apply it for instance with
There are no data alignment restrictions on op, any address is allowed.
Here's an example converting an array of
unsigned longdata, most significant element first, and host byte order within each value.unsigned long a; /* Initialize z and a */ mpz_import (z, 20, 1, sizeof(a), 0, 0, a);
This example assumes the full
sizeofbytes are used for data in the given type, which is usually true, and certainly true for
unsigned longeverywhere we know of. However on Cray vector systems it may be noted that
intare always stored in 8 bytes (and with
sizeofindicating that) but use only 32 or 46 bits. The nails feature can account for this, by passing for instance
The parameters specify the format of the data produced. Each word will be size bytes and order can be 1 for most significant word first or -1 for least significant first. Within each word endian can be 1 for most significant byte first, -1 for least significant first, or 0 for the native endianness of the host CPU. The most significant nails bits of each word are unused and set to zero, this can be 0 to produce full words.
The number of words produced is written to
*countp, or countp can be
NULLto discard the count. rop must have enough space for the data, or if rop is
NULLthen a result array of the necessary size is allocated using the current GMP allocation function (see Custom Allocation). In either case the return value is the destination used, either rop or the allocated block.
If op is non-zero then the most significant word produced will be non-zero. If op is zero then the count returned will be zero and nothing written to rop. If rop is
NULLin this case, no block is allocated, just
The sign of op is ignored, just the absolute value is exported. An application can use
mpz_sgnto get the sign and handle it as desired. (see Integer Comparisons)
There are no data alignment restrictions on rop, any address is allowed.
When an application is allocating space itself the required size can be determined with a calculation like the following. Since
mpz_sizeinbasealways returns at least 1,
counthere will be at least one, which avoids any portability problems with
malloc(0), though if
zis zero no space at all is actually needed (or written).numb = 8*size - nail; count = (mpz_sizeinbase (z, 2) + numb-1) / numb; p = malloc (count * size);