shithub: femtolisp

ref: 36b24a92d94b1d1f100746d27d13fc77f1599201
dir: /3rd/mp/mprand.c/

View raw version
#include "platform.h"
#include "mp.h"

mpint *
mprand(int bits, void (*gen)(uint8_t*, int), mpint *b)
{
	mpdigit mask;

	if(b == nil)
		b = mpnew(bits);
	else
		mpbits(b, bits);

	b->sign = 1;
	b->top = DIGITS(bits);
	(*gen)((uint8_t*)b->p, b->top*Dbytes);

	mask = ((mpdigit)1 << (bits%Dbits))-1;
	if(mask != 0)
		b->p[b->top-1] &= mask;

	return mpnorm(b);
}