fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. // macro that defines the size of an integer
  5. // assuming 2 byte storage for integer
  6. #define SIZE 16
  7.  
  8. // Function to add x and y in binary
  9. int* add(int x, int y)
  10. {
  11. int carry = 0;
  12. int n = SIZE;
  13.  
  14. // create a array to store binary sum
  15. int* arr = (int*)malloc(n);
  16.  
  17. for (int i = 0; i < n; i++)
  18. {
  19. // if x is 1
  20. if (x & (1 << i))
  21. {
  22. // if y is 1
  23. if (y & (1 << i)) // if both x and y are 1
  24. {
  25. if (carry)
  26. arr[n - i - 1] = 1; // carry = 1
  27. else
  28. arr[n - i - 1] = 0, carry = 1;
  29. }
  30. else // x is 1, y is 0
  31. {
  32. if (carry)
  33. arr[n - i - 1] = 0; // carry = 1
  34. else
  35. arr[n - i - 1] = 1; // carry = 0
  36. }
  37. }
  38. // if x is 0
  39. else
  40. {
  41. if (y & (1 << i)) // x is 0, y is 1
  42. {
  43. if (carry)
  44. arr[n - i - 1] = 0; // carry = 1
  45. else
  46. arr[n - i - 1] = 1; // carry = 0
  47. }
  48. else // both x and y are 0
  49. {
  50. if (carry == 1)
  51. arr[n - i - 1] = 1, carry = 0;
  52. else
  53. arr[n - i - 1] = 0; // carry = 0
  54. }
  55. }
  56. }
  57.  
  58. return arr;
  59. }
  60.  
  61. int main()
  62. {
  63. int x = 12731, y = 38023;
  64.  
  65. cout << "x (" << x << ") in binary is " << bitset<16>(x) << endl;
  66. cout << "y (" << y << ") in binary is " << bitset<16>(y) << endl;
  67.  
  68. int* arr = add(x, y);
  69.  
  70. cout << "\nx + y is ";
  71. for (unsigned i = 0; i < SIZE; i++)
  72. printf("%d", arr[i]);
  73.  
  74. return 0;
  75. }
  76.  
Success #stdin #stdout 0s 3472KB
stdin
Standard input is empty
stdout
x (12731) in binary is 0011000110111011
y (38023) in binary is 1001010010000111

x + y is 1100011001000010