使用 & ^ << 等 位符實現加法運算

來源:互聯網
上載者:User

標籤:des   blog   使用   2014   os   name   

學習過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;}

代碼測試:

[[email protected] Destop]$ gcc -o bin_add test.c[[email protected] Destop]$ ./bin_add  10 789(10)+(789)=799[[email protected] Destop]$ ./bin_add  1234  4567(1234)+(4567)=5801[[email protected] Destop]$ ./bin_add  1234  -456(1234)+(-456)=778[[email protected] Destop]$ ./bin_add  -34  -456(-34)+(-456)=-490

其實主要就是解決加法過程中分開 “本位和”  和 “進位和” ;一次一次把進位加到自己的位置上就可以了。



相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.