title: Performing arithmetic operations in binary using only bitwise operators
body: <blockquote>
    <p><strong>Possible Duplicate:</strong><br>
    <a href="https://stackoverflow.com/questions/2776211/how-can-i-multiply-and-divide-using-only-bit-shifting-and-adding">How can I multiply and divide using only bit shifting and adding? </a>  </p>
  </blockquote>
  
  
  
  <p>I have to write functions to perform binary subtraction, multiplication, and division without using any arithmetic operators except for loop control. I've only written code in Java before now, so I'm having a hard time wrapping my head around this.</p>
  
  <p>Starting with subtraction, I need to write a function with prototype </p>
  
  <pre><code>int bsub(int x, int y)
  </code></pre>
  
  <p>I know I need to convert y to two's complement in order to make it negative and add it to x, but I only know how to do this by using one's complement ~ operator and adding 1, but I can't use the + operator. </p>
  
  <p>The badd function was provided, and I will be able to implement it in bsub if I can figure out how to make y a negative number. The code for badd is shown below. Thanks in advance for any tips. </p>
  
  <pre><code>int badd(int x,int y){
  
  int i;
  
  char sum;
  char car_in=0;
  char car_out;
  char a,b;
  
  unsigned int mask=0x00000001;
  int result=0;
  
  for(i=0;i&lt;32;i++){
  
    a=(x&amp;mask)!=0;
    b=(y&amp;mask)!=0;
    car_out=car_in &amp; (a|b) |a&amp;b;
    sum=a^b^car_in;
  
    if(sum) {
       result|=mask;
    }
  
    if(i!=31) {
       car_in=car_out;
    } else {
       if(car_in!=car_out) {
          printf("Overflow occurred\n");
       }
    }
  
    mask&lt;&lt;=1;
    }
  
   return result;
    }
  </code></pre>