int addMBInt1(MBigInt* dst, MBigInt* src1, MBigInt* src2)
{
long int len = 0; //兩個大整數的長度最大值
long int dstlen = 0; //目標數組分配的最大值
un_short mark = 0;//進位標誌
unsigned int result;//數組對應元素相加結果
long sign = src1->sign;//整數的符號
int i = 0;
len = (src1->length >= src2->length)?src1->length:src2->length;
dstlen = len;
if(-1 == extendMBInt(dst,len))//擴展足夠內存
{
return 0;
}
//較小數位的整數的長度
len = (src1->length>src2->length)? src2->length: src1->length;
for(i = 0; i < len; i++) //對兩個大整數的數位相同部分進行計算
{
result = src1->pBigInt[i] + src2->pBigInt[i] + mark;
dst->pBigInt[i] = (result&0xffff);
mark = result >> 16;
}
//對第壹個大整數數位多出部分進行計算
if(src1->length > src2->length)
{
while(i < src1->length)
{
result = src1->pBigInt[i] + mark;
dst->pBigInt[i] = result & 0xffff;
mark = result >> 16;
i++;
}
if(mark != 0)
{
dst->pBigInt[i] = mark;
}
dstlen = src1->length + 1;
}
//對第二個大整數數位多出部分進行計算
else if(src1->length < src2->length)
{
while(i < src2->length)
{
result = src2->pBigInt[i] + mark;
dst->pBigInt[i] = result & 0xffff;
mark = result >> 16;
i++;
}
if(mark != 0)
{
dst->pBigInt[i] = mark;
}
dstlen = src2->length + 1;
}
dst->sign = sign; //符號的更改
dst->length = dstlen; // 長度設置
return 1;
}
int extendMBInt(MBigInt *mbi,long int size)
{
if(mbi->alloclen < size)
{
long int i = 0;
un_short *pt = NULL;
long int newAlloc = mbi->alloclen;
while(newAlloc< size)
{ /* 分配至少能容納size個元素的長度,步進為STEP_BINT */
newAlloc += STEP_BINT;
}
if((pt = (un_short *)realloc(mbi->pBigInt,sizeof(un_short)*newAlloc)) == NULL)
return FAILE_MEMORY_BINT;
mbi->pBigInt = pt;
for(i = mbi->alloclen; i < newAlloc; ++i) /* 對新的元素置0*/
{
mbi->pBigInt[i] = 0;
}
mbi->alloclen= newAlloc;
}
return RETURN_OK_BINT;
}