Skip to main content
2 of 4
edited tags
Katie
  • 43
  • 1
  • 7

C++ Adding Two 16 bit binary numbers together

I am trying to add two 16 digit binary numbers together. Each binary number will have been entered by the user and saved as: binaryOne[16] and binaryTwo[16]. This is what I have so far:

void Solution() {
  /*
    Rule of binary addition:
    0 + 0 = 0
    1 + 0 = 1
    0 + 1 = 1
    1 + 1 = 1 and carry = 1
   */
   lcd.clear();
   lcd.setCursor(0,0);
   lcd.print("Solution");
   lcd.setCursor(0,2);
   
   
   


    int a[16] = binaryOne[16];
    int b[16] = binaryTwo[16];
    int i = 0;
    int remainder = 0;
    int sum[32];

    while(a[16] != 0 || b[16] != 0){
      sum[i++] = (a[16] % 10 + b[16] % 10 + remainder) % 2;
      remainder = (a[16] % 10 + b[16] % 10 + remainder) / 2; 
      a[16] = a[16] /10;
      b[16] = b[16] / 10;
    }
    if(remainder != 0){
      sum[i++] = remainder;
    }
    i--;
    while(i>=0){
      lcd.print("%d", sum[i--]);
   }
   return 0;
}

I believe I am doing something wrong with calling the arrays since I am renaming them to a[16] and b[16] within this function. I'm also curious, since I only have 16 bits of space on the screen, what if the user enters a binary number such as 1111111111111111 + 1000000000000000 and therefor there is going to be a carry on that first digit? Would it be best just to have an error message?

Katie
  • 43
  • 1
  • 7