How can I convert a 16-bit int to a signed 8-bit int?

Viewed 60

I'm trying to add two 8-bit integers without the use of (+) or (-) operators and conditionals/loops - using only bitwise operators. Here's my code:

   short int one, two, carry, exor; 
   cout<<"Enter number 1: "; cin>>one;
   cout<<"\nEnter number 2: ";
   cin>>two;
   carry = (one & two)<<1;
   exor = (one ^ two);
   one = (carry & exor)<<1;
   two = (carry ^ exor);
   carry = (one & two)<<1;
   exor = (one ^ two);
   one = (carry & exor)<<1;
   two = (carry ^ exor);
   carry = (one & two)<<1;
   exor = (one ^ two);
   one = (carry & exor)<<1;
   two = (carry ^ exor);
   carry = (one & two)<<1;
   exor = (one ^ two);
   carry = (carry & 0b000000011111111);
   exor = (exor & 0b000000011111111);
   cout<<"\nOutput: "<<(carry ^ exor)<<endl;
    

Since I can't use a loop or conditional, I instead reassign the 'carry' /'exor' value to one and two and vice versa 4 times so I'm left with a '0' in the carry for all cases. In the end, I need my value to work for 8-bit integers and 8-bit integers only - which is why i use the & operator with 0b000000011111111 to convert it into an 8-bit integer. However, this conversion gives me an unsigned 8-bit integer range from 0 to 255, causing an overflow whenever the result of the calculation is <0. How can I convert the 'carry' / 'exor' variables to signed 8-bits so the range is -128 to 127?

0 Answers
Related