AntonioVillanueva

Suma binaria ....

Feb 29th, 2016
185
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.23 KB | None | 0 0
  1. //compilacion g++ -std=c++11 -o NombreEjecutable NombreFuente.cpp
  2. //SUMA BINARIA bit a bit utilizando carry
  3. #include <iostream>
  4. using namespace std;
  5. #define uno 0xFF
  6. #define X(i) (x & bit)
  7. #define Y(i) (y & bit)
  8. #define Cy(i) (carry & bit)
  9.  
  10. int suma (unsigned char x,unsigned char y,unsigned char carry=0,size_t max_bits=128){
  11.     unsigned char d(0);
  12.     for (size_t bit=1;bit<=max_bits; bit=bit<<1){//Desplaza un bit hacia izq.
  13.         //suma bit a bit teniendo en cuenta el carry
  14.         d |= X(i) ^ Y(i)  ^ Cy(i)  ;
  15.                        
  16.         //en una suma binaria 1 + 1 =0 y me llevo 1 carry,carry uno                
  17.         ((!(X(i) ^ Y(i)  ^ Cy(i)) && ( X(y) | Y(y) | Cy(i) )) || X(y) & Y(i) & Cy(i)) ? carry=uno : carry=0;
  18.                
  19.         cout <<"bit="<<bit<<'\t' << ", x= "<< (X(i) ? " 1 ": " 0 ") << " , y= " << (Y(i) ? " 1 ": " 0 ")<< " , cy= "<< (Cy(i) ? " 1 ": " 0 ")<<endl;
  20.        
  21.     }  
  22.     return d;  
  23. }
  24. int main (){
  25.    
  26.     cout <<suma (8,8) << endl;//16
  27.     cout <<suma (8,7) << endl;//15
  28.     cout <<suma (9,7) << endl;//16
  29.     cout <<suma (10,7) << endl;//17
  30.     cout <<suma (11,7) << endl;//18
  31.     cout <<suma (25,25) << endl;//50  
  32.     cout <<suma (127,127) << endl;//254
  33.    
  34.     return 0;
  35. }
Add Comment
Please, Sign In to add comment