libcurve/src/mpztools.c

50 lines
1013 B
C

#include <mpztools.h>
#include <stdlib.h>
#include <stdio.h>
#include <rand.h>
#include <gmp.h>
mpz_t* mpz_field_init(int length)
{
int *l = malloc( sizeof(int) + (sizeof(mpz_t) * length));
*l = length;
mpz_t *f = (mpz_t*) (++l);
for (int n=0;n<length;n++)
mpz_init(f[n]);
return f;
}
void mpz_field_clear(mpz_t *f)
{
int *l = ((int*)f)-1;
for (int n=0;n<*l;n++)
mpz_clear(f[n]);
free(l);
}
void mpz_random_mod( mpz_t rop, mpz_t p)
{
int bytesize = (mpz_sizeinbase( p, 2 )+7) >> 3;
char b[ bytesize * 2 ];
rand_get_bytes( b, bytesize * 2 );
mpz_import( rop, bytesize * 2, -1, 1, -1, 0, b );
mpz_mod( rop, rop, p );
}
char* mpz_to_string(mpz_t i, int base)
{
static char *s = NULL;
static int slen = 0;
int neededsize = mpz_sizeinbase(i, base) + 2;
if (slen < neededsize)
{
if (s)
free(s);
s = malloc(neededsize);
slen = neededsize;
}
mpz_get_str(s, base, i );
return s;
}