Problem with GMP mpz bit functions
Erik Beese
erikbeese at cogeco.ca
Wed Nov 12 09:42:22 CET 2003
I've been trying to use the GMP library to express strings as very large
numbers using bit mapping. converting from an arbitrary string works
well but I've been having no luck with the reverse, recovering the
string from a mpz_t using bit-testing.
here is the current code for the two functions.
I started with mpz_tstbit but like it states at the end of the code
block it always returned 1. Am I missing something?
Thanks Erik
***begin codeblock***
int bitwise_string_to_mpz_t (char *mystring, mpz_t mympz, int bytes)
{
//this will *reverse* the bitorder of the string. since the number is
random
//this should not make any difference in randomness
unsigned long int bitnum;
unsigned long int currbit;
unsigned char mychar;
int currbyte;
bitnum = 0;
//below is a kludge but it might just work
for (currbyte = 0; currbyte < bytes ; currbyte++)
{
//set mychar
mychar = mystring[currbyte];
(mychar == (CBIT7 ^ mychar)) ? : mpz_setbit (mympz, bitnum);
bitnum++;
(mychar == (CBIT6 ^ mychar)) ? : mpz_setbit (mympz, bitnum);
bitnum++;
(mychar == (CBIT5 ^ mychar)) ? : mpz_setbit (mympz, bitnum);
bitnum++;
(mychar == (CBIT4 ^ mychar)) ? : mpz_setbit (mympz, bitnum);
bitnum++;
(mychar == (CBIT3 ^ mychar)) ? : mpz_setbit (mympz, bitnum);
bitnum++;
(mychar == (CBIT2 ^ mychar)) ? : mpz_setbit (mympz, bitnum);
bitnum++;
(mychar == (CBIT1 ^ mychar)) ? : mpz_setbit (mympz, bitnum);
bitnum++;
(mychar == (CBIT0 ^ mychar)) ? : mpz_setbit (mympz, bitnum);
bitnum++;
}
return SUCCESS;
}
int bitwise_mpz_t_to_string (char *mystring, mpz_t mympz, unsigned long
int bits)
{
//this will *reverse* the bitorder back to original
mpz_t bar;
unsigned long int currbit;
unsigned char mychar;
strcpy(mystring,"\0");
mpz_init (bar);
mpz_add (bar, bar, mympz);
mychar = 0;
mpz_mul_ui (bar, bar, 2);
gmp_printf ("%Zd\n", bar);
mpz_div_ui (bar, bar, 2);
gmp_printf ("%Zd\n", bar);
for (currbit = 0 ; currbit < bits ; currbit++)
{
mpz_setbit (mympz, currbit);
if (mpz_cmp(bar, mympz) == 0)
{
mychar <<= 1;
mychar += 1;
}
else
{
mychar <<= 1;
mpz_setbit (mympz, currbit);
}
if ((currbit % 8) == 7)
{
strcat(mystring, &mychar);
mychar = 0;
}
}
}
***end codeblock***
Text in:
"Hello This is a Test"
Numeric Value:
1461501637330902918203684832716283019655932542975
This never changes even when it is poked with mpz_setbit and mpz_clrbit
in bitwise_mpz_t_to_string()
mpz_tstbit always returns 1
mpz_popcount = 160
mpz_mul*
mpz_div*
mpz_add*
mpz_sub*
all work as per usual
More information about the gmp-discuss
mailing list