c语言问题 大家帮帮忙啊!
编一个程序,完成64位数据(无符号)的加法,减法运算.不允许直接使用64位的数据类型
[解决办法]
#include <cstdlib>
#include <iostream>
using namespace std;
typedef struct
{
unsigned int high;
unsigned int low;
} Int64_t;
Int64_t add(Int64_t x,Int64_t y)
{
unsigned int carry;//进位
unsigned int h1,h2,h3;
Int64_t tmp;
tmp.low=x.low+y.low;
h1=tmp.low> > 31;
h2=x.low> > 31;
h3=y.low> > 31;
if ((h1==0 && h2==1 ) || (h1==0 && h3==1 ) || (h1==1 && h2==1 && h3==1))
carry=1;
else
carry=0;
tmp.high=x.high+y.high+carry;
return tmp;
}
int main(int argc, char *argv[])
{
Int64_t a, b,result;
a.high=0x3;
a.low=0xFFFFFFFF;
b.high =0x3;
b.low=0xFFFFFFFF;
result=add(a,b);
printf( "%08x%08x ",result.high, result.low);
system( "PAUSE ");
return 0;
}
[解决办法]
typedef struct
{
unsigned char su[8];
} Int64_t;
Int64_t add(Int64_t x,Int64_t y)
{
unsigned int carry,m;//进位
unsigned int i;
Int64_t temp;
carry=0;
for(i=0;i <8;i++)
{
temp.su[i]=x.su[i]+y.su[i]+carry;
m=x.su[i]+y.su[i]+carry;
if(m&(1 < <8)) carry=1;
else carry=0;
}
return temp;
}
int main(int argc, char *argv[])
{
Int64_t a, b,result;
a.high=0x3;
a.low=0xFFFFFFFF;
b.high =0x3;
b.low=0xFFFFFFFF;
result=add(a,b);
system( "PAUSE ");
return 0;
}