Search code examples
cgmp

GMP (MPIR) - keep leading zeros when init


I'm working on a program where we read in a string of ones and zeroes "0 0 0 0 1 1 0 0 0 ..." etc as input.

For part of the program, we need to convert this string to a bit vector/array of bits. Conveniently, mpz_init_set_str offers this functionality in the GMP library (the rest of the program uses GMP to speed up computation).

However, what happens is that the first set of zeroes get ignored until we hit a one because mpz_init_set_str discards leading zeroes: https://github.com/alisw/GMP/blob/master/mpz/set_str.c#L103

Is there a function within the GMP library such that mpz_init_set_str does not ignore leading zeroes?

I realize I could modify the GMP library to get around the issue, but I think that would be painful for users to install.

while ((bytesRead = fread(buffer, 1, 8192, file)) > 0)
        {
            mpz_init_set_str(res, buffer, 2);
            mpz_export(buff, &result, 1, 1, 0, 0, res);
            for (size_t i = 0; i < result; i++) {
                fputc(buff[i], fptr);
            }
            mpz_clear(res);
        }

Solution

  • Added "fake" 1 and then got that bit and convert back to its old value:

    unsigned char newCh = (char)((int)buff[0] - 128);