您的位置:首页 > 其它

位运算实现加减乘除

2013-06-26 13:35 316 查看
#include <stdio.h>
#include <limits.h>

//加法运算
int add(int a, int b)
{
return b==0 ? a: add(a^b,(a&b)<<1);
}

//补码中正数转负数的原理
int negative(int a)
{
return add(1,~a);
}

//减法运算
int sub(int a,int b)
{
return add(a,negative(b));
}

//判断正负
bool isNegative(int a)
{
return (a&INT_MIN)!=0; //INT_MIN只有最高位为1,其余位为0
}

//仅计算正数乘法
int multi_help(int a,int b)
{
int result= 0;
while(b)
{
if(b&1) result = add(result, a);
a <<=1;
b >>= 1;
}
return result;
}

//乘法
int multi(int a,int b)
{
if(isNegative(a))
{
if(isNegative(b))
return multi_help(negative(a),negative(b));
else
return negative(multi_help(negative(a),b));
}
else
{
if(isNegative(b))
return negative(multi_help(a,negative(b)));
else
return multi_help(a,b);
}
}

//仅计算正数除法
int div_help(int a,int b)
{
if(a<b) return 0;
if(a==b) return 1;
int result=0;
//第32位为符号位,所以从第31位开始
for(int i=30;i>=0;i--)
{
if((a>>i)>=b)
{
result=add(result,1<<i);
a=sub(a,b<<i);
}
}
return result;
}
//除法
int div(int a,int b)
{
if(isNegative(a))
{
if(isNegative(b))
return div_help(negative(a),negative(b));
else
return negative(div_help(negative(a),b));
}
else
{
if(isNegative(b))
return negative(div_help(a,negative(b)));
else
return div_help(a,b);
}
}

int main(void)
{
int a,b;
a=-30;
b=-5;
printf("ADD:%d,SUB:%d,MULTI:%d,DIV:%d",add(a,b),sub(a,b),multi(a,b),div(a,b));
return 0;
}
转载自:http://blog.csdn.net/xinhanggebuguake/article/details/7475804
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: