fork(1) download
  1. #include <stdio.h>
  2.  
  3. int bit[] = { 1<<0, 1<<1, 1<<2, 1<<3 };
  4.  
  5. struct fullAdderReturn
  6. {
  7. int sum;
  8. int carryOut;
  9. };
  10.  
  11. typedef struct fullAdderReturn FAR_t;
  12.  
  13. FAR_t oneBitAdder(int a, int b, int carryIn)
  14. {
  15. FAR_t output;
  16. output.sum = a^b^carryIn;
  17. output.carryOut = (a&b) | (a&carryIn) | (a&carryIn);
  18.  
  19. return output;
  20. }
  21.  
  22. FAR_t twoBitAdder(int a, int b, int carryIn)
  23. {
  24. FAR_t output, temp;
  25. output.sum = 0;
  26.  
  27. //add the least significant bits
  28. temp = oneBitAdder(a&bit[0], b&bit[0], carryIn);
  29.  
  30. //set the sum
  31. output.sum |= temp.sum << 0;
  32.  
  33. //add the next bits using carry from last add
  34. temp = oneBitAdder(a&bit[1], b&bit[1], temp.carryOut);
  35.  
  36. //shift up the output and or it together with result of last add
  37. output.sum |= ((temp.sum) << 1);
  38. output.carryOut = temp.carryOut;
  39.  
  40. return output;
  41. }
  42.  
  43. int main( void )
  44. {
  45. int a = 1;
  46. int b = 1;
  47.  
  48. int carryIn = 1;
  49.  
  50.  
  51. FAR_t t = twoBitAdder(a, b, carryIn);
  52.  
  53. printf("sum = %d, carryOut = %d\n", t.sum, t.carryOut);
  54.  
  55. return 0;
  56. }
Success #stdin #stdout 0s 1832KB
stdin
Standard input is empty
stdout
sum = 3, carryOut = 0