typedef unsigned int u32;
typedef unsigned char u8;
typedef unsigned short u16;
typedef unsigned long long u64;
// 数据拷贝
void Data_u4_CopyBuffer(u32 *p_dst, u32 *p_src,u32 len)
{
// Compare source address and destination address to know
// the order (forward or backward copy)
if (p_src>p_dst)
{
// forward copy
while(len--)
{
*(p_dst++)=*(p_src++);
}
}
else
{
p_src+=len;
p_dst+=len;
// backward copy
while(len--)
{
*(--p_dst)=*(--p_src);
}
}
return;
}
/******************************************************************************
a = a + 1;
if overflow, return 1
******************************************************************************/
u32 BigInc(u32*a,u32 len)
{
u32 i;
u32 c = 1; /* carry */
for(i = 0; c && i!=len; i++)
{
a[i]++; //a[i]+1,若溢出,就会变成0000 0000
if(a[i]) //a[i]非0,返回0
{
c = 0;
}
else //a[i]=0时,c = 1,继续查看下一个数
{
c = 1;
}
}
return c;
}
/******************************************************************************
unsigned integer add
if overflow, return 1
res = a + b(res的长度为uLen)
此函数仅支持相同长度的大数相加
******************************************************************************/
u32 BigAdd(u32 *Sum,u32 *Augend,u32 *Addend,u32 ulLen)
{
u32 carry=0;
u64 _W;
while (ulLen--)
{
_W = (u64)carry + (u64)(*Augend++) + (u64)(*Addend++);
*Sum++ = (u32)_W;
carry = (u32)(_W >> 32);
}
return carry;
}
// 上述大数加法的扩展版
// Sum的长度为AugendlLen>AddendLen?AugendlLen+1:AddendLen+1
void BigAdd_Extra(u32 *Sum,u32 *Augend,u32 *Addend,u32 AugendlLen,u32 AddendLen)
{
if (AugendlLen>AddendLen)
{
Data_u4_CopyBuffer(Sum+AddendLen,Augend+AddendLen,AugendlLen-AddendLen);
Sum[AugendlLen]=0x00;
if (BigAdd(Sum,Augend,Addend,AddendLen)!=0)
{
BigInc(Sum+AddendLen,AugendlLen-AddendLen+1);
}
}
else
{
Data_u4_CopyBuffer(Sum+AugendlLen,Addend+AugendlLen,AddendLen-AugendlLen);
Sum[AddendLen]=0x00;
if (BigAdd(Sum,Augend,Addend,AugendlLen)!=0)
{
BigInc(Sum+AugendlLen,AddendLen-AugendlLen+1);
}
}
}
// 数据翻转
void top_swap_bottom(u32 *res,u32 resLen)
{
int i;
for (i=0;i<resLen/2;i++)
{
res[i] = res[i] ^res[resLen-i-1];
res[resLen-i-1]= res[i] ^res[resLen-i-1];
res[i] = res[i] ^res[resLen-i-1];
}
}
// 举个例子
int main()
{
u32 res[10]={0x00};
u32 a[8]={0x00223344,0x99887766,0x00223344,0x99887766,0x00223344,0x99887766,0x00223344,0x99887766};
u32 b[9]={0x00223344,0x99887766,0x00223344,0x99887766,0x00223344,0x99887766,0x00223344,0x99887766,0x99776655};
top_swap_bottom(a,8);
top_swap_bottom(b,9);
BigAdd_Extra(res,a,b,8,9);
top_swap_bottom(res,10);
return 0;
}