Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //compilacion g++ -std=c++11 -o NombreEjecutable NombreFuente.cpp
- //SUMA BINARIA bit a bit utilizando carry
- #include <iostream>
- using namespace std;
- #define uno 0xFF
- #define X(i) (x & bit)
- #define Y(i) (y & bit)
- #define Cy(i) (carry & bit)
- int suma (unsigned char x,unsigned char y,unsigned char carry=0,size_t max_bits=128){
- unsigned char d(0);
- for (size_t bit=1;bit<=max_bits; bit=bit<<1){//Desplaza un bit hacia izq.
- //suma bit a bit teniendo en cuenta el carry
- d |= X(i) ^ Y(i) ^ Cy(i) ;
- //en una suma binaria 1 + 1 =0 y me llevo 1 carry,carry uno
- ((!(X(i) ^ Y(i) ^ Cy(i)) && ( X(y) | Y(y) | Cy(i) )) || X(y) & Y(i) & Cy(i)) ? carry=uno : carry=0;
- cout <<"bit="<<bit<<'\t' << ", x= "<< (X(i) ? " 1 ": " 0 ") << " , y= " << (Y(i) ? " 1 ": " 0 ")<< " , cy= "<< (Cy(i) ? " 1 ": " 0 ")<<endl;
- }
- return d;
- }
- int main (){
- cout <<suma (8,8) << endl;//16
- cout <<suma (8,7) << endl;//15
- cout <<suma (9,7) << endl;//16
- cout <<suma (10,7) << endl;//17
- cout <<suma (11,7) << endl;//18
- cout <<suma (25,25) << endl;//50
- cout <<suma (127,127) << endl;//254
- return 0;
- }
Add Comment
Please, Sign In to add comment