學習過C語言的同學都知道,再寫代碼的時候,位操作運算總比算數運算操作快,
本文就是用C語言提供的位運算實現兩個數的加法。
本文使用的代碼都經過調試正常並且能夠運行,調試環境centos gcc 一下是實現代碼,以及測試結果:
#include<stdio.h>
#include<stdlib.h>
int main(int argc, char **argv)
{
int add_a,add_b;
int sum;
if(3!=argc)
printf("usage : bin_add , (#add_1) (#add_d)\n");
else
{
add_a= atoi(argv[1]);
add_b= atoi(argv[2]);
sum =add(add_a,add_b);
printf("(%d)+(%d)=%d\n",add_a,add_b,sum);
}
return 0;
}
int add(int temp_a,int temp_b)
{
int temp_c=0;
int temp_d=0;
temp_c=temp_a & temp_b; //求進位
temp_d=temp_a ^ temp_b; //求本位和
while(temp_c)
{
temp_c<<=1;
temp_b=temp_c;
temp_a=temp_d;
temp_c=temp_a & temp_b;
temp_d=temp_a ^ temp_b;
}
return temp_d;
}
代碼測試:
[trageday@trageday Destop]$ gcc -o bin_add test.c
[trageday@trageday Destop]$ ./bin_add 10 789
(10)+(789)=799
[trageday@trageday Destop]$ ./bin_add 1234 4567
(1234)+(4567)=5801
[trageday@trageday Destop]$ ./bin_add 1234 -456
(1234)+(-456)=778
[trageday@trageday Destop]$ ./bin_add -34 -456
(-34)+(-456)=-490
其實主要就是解決加法過程中分開 “本位和” 和 “進位和” ;一次一次把進位加到自己的位置上就可以了。
使用遞歸實現加法:
int add_digui(int temp_a,int temp_b)
{
int temp_sum,carry;
if(temp_b==0)
return temp_a;
temp_sum=temp_a^temp_b;//本位和
carry =(temp_a&temp_b)<<1;//進位
add_digui(temp_sum,carry);
}
還是遞歸實現的比較簡單明瞭。