shithub: femtolisp

ref: d0505fae65fce8e65074561301f2257450c22339
dir: /3rd/mp/mptoi.c/

View raw version
#include "platform.h"

/*
 *  this code assumes that mpdigit is at least as
 *  big as an int.
 */

mpint*
itomp(int i, mpint *b)
{
	if(b == nil){
		b = mpnew(0);
	}
	b->sign = (i >> (sizeof(i)*8 - 1)) | 1;
	i *= b->sign;
	*b->p = i;
	b->top = 1;
	return mpnorm(b);
}

int
mptoi(mpint *b)
{
	mpdigit x;

	if(b->top==0)
		return 0;
	x = *b->p;
	if(b->sign > 0){
		if(b->top > 1 || x > INT32_MAX)
			x = (int)INT32_MAX;
		else
			x = (int)x;
	} else {
		if(b->top > 1 || x > (mpdigit)INT32_MAX+1)
			x = (int)INT32_MIN;
		else
			x = -(int)x;
	}
	return x;
}