Thread: C++ Binary Addition

  1. #1
    Registered User
    Join Date
    Nov 2010
    Posts
    5

    C++ Binary Addition

    I am trying to write a program that adds any pair of binary numbers up to 31 digits correctly.

    I am having a very difficult time with this. I can't figure out how to let it accept 31 digits, how to add two numbers that are not the same amount of digits like 1001 and 101, and I can't get it to work with getch().

    Any help would be great!

    Code:
    #include<stdio.h>
    #include<curses.h>
    
    
    int main()
    {
        int a[8],b[8],c[9], carry=0;
        int i,j;
        //int sum;
        printf("Enter the First Eight bit number: ");
        for(i=0;i<8;i++)
        {
            scanf("%d",&a[i]);
        }
        printf("\nEnter the Second Eight bit number: ");
        for(i=0;i<8;i++)
        {
            scanf("%d",&b[i]);
        }
        
        j=8;
        for(i=7;i>=0;i--)
        {
            if (a[i]==1 && b[i]==1 && carry ==1)
            {
                c[j] = 1;
                carry =1;
            }
            else if (a[i]==1 && b[i]==1 && carry ==0)
            {
                c[j]=0;
                carry=1;
            }
            else if (a[i]==0 && b[i]==1 && carry ==0)
            {
                c[j]=1;
                carry=0;
            }
            else if (a[i]==0 && b[i]==1 && carry ==1)
            {
                c[j]=0;
                carry=1;
            }
            else if (a[i]==1 && b[i]==0 && carry ==1)
            {
                c[j]=0;
                carry=1;
            }
            else if (a[i]==1 && b[i]==0 && carry ==0)
            {
                c[j]=1;
                carry=0;
            }
            else if (a[i]==0 && b[i]==0 && carry ==1)
            {
                c[j]=1;
                carry=0;
            }
            else if (a[i]==0 && b[i]==0 && carry ==0)
            {
                c[j]=0;
                carry=0;
            }
            
            j--;
            
        }
        c[0] = carry;
        
        printf("\nthe sum of the two binary number is: ");
        for(j=0;j<=8;j++)
        {
            printf("%d",c[j]);
        }
        getch();
        return 0;
    }

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,660
    Well if you're using scanf like that, you need to enter "1 0 0 1" rather than "1001"
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  3. #3
    Registered User
    Join Date
    Nov 2010
    Posts
    5
    The thing is I can't even get it to start because of getch()

  4. #4
    Registered User
    Join Date
    May 2011
    Location
    Around 8.3 light-minutes from the Sun
    Posts
    1,949
    Quote Originally Posted by HBlakeH View Post
    The thing is I can't even get it to start because of getch()
    getch() isn't standard and probably not supported by your compiler then. Don't use it, take a look at How to keep my console window open-FAQ

    EDIT: An this isn't C++, it's C.
    Last edited by AndrewHunter; 09-14-2011 at 11:42 AM.
    Quote Originally Posted by anduril462 View Post
    Now, please, for the love of all things good and holy, think about what you're doing! Don't just run around willy-nilly, coding like a drunk two-year-old....
    Quote Originally Posted by quzah View Post
    ..... Just don't be surprised when I say you aren't using standard C anymore, and as such,are off in your own little universe that I will completely disregard.
    Warning: Some or all of my posted code may be non-standard and as such should not be used and in no case looked at.

  5. #5
    Registered User
    Join Date
    Nov 2010
    Posts
    5
    I have changed my code with the help from a classmate but the output is a zero with 31 ones with the input: 1001 101

    It is supposed to take in arguments from the command line.
    ex:
    g++ main.cpp
    ./a.out 1001 101

    Can anyone help me figure this out?

    Code:
    #include <iostream>
    #include <cstdlib>
    
    using namespace std;
    
    int main(int argc, char* argv[])
    {
    	if(argc != 3)
    	{
    		cerr << "Invalid number of operands" << endl;
    		return 1;
    	}
        
    	int i;
    	int num1 = atoi(argv[1]); //converts char -> int
    	int num2 = atoi(argv[2]); //#include <cstdlib>
        int a1[i];
        int b1[i];
        int c[32];
    	int carry = 0;
        int j;
        
        j = 31;
        
        for(i = 0; i < 32; i++)
        {
            a1[i] = num1/10;
            num1 %= 10;
        }
        
        for(i = 0; i < 32; i++)
        {
            b1[i] = num2/10;
            num2 %= 10;
        }
        
        for(i = 30 ; i >= 0; i--)
        {
            if (num1 == 1 && num2 == 1 && carry == 1)
            {
                c[j] = 1;
                carry = 1;
            }
            else if (num1 == 1 && num2 == 1 && carry == 0)
            {
                c[j] = 0;
                carry = 1;
            }
            else if (num1 == 0 && num2 == 1 && carry == 0)
            {
                c[j] = 1;
                carry = 0;
            }
            else if (num1 == 0 && num2 == 1 && carry == 1)
            {
                c[j] = 0;
                carry = 1;
            }
            else if (num1 == 1 && num2 == 0 && carry == 1)
            {
                c[j] = 0;
                carry = 1;
            }
            else if (num1 == 1 && num2 == 0 && carry == 0)
            {
                c[j] = 1;
                carry = 0;
            }
            else if (num1 == 0 && num2 == 0 && carry == 1)
            {
                c[j] = 1;
                carry = 0;
            }
            else if (num1 == 0 && num2 == 0 && carry == 0)
            {
                c[j] = 0;
                carry = 0;
            }
            
            j--;
        }
        c[0] = carry;
        
        cout << "Blake Beavers" << endl;
        for(j = 31; j >= 0; j--)
        {
            cout << c[j];
        }
        cout << endl;
    	return 0;
    }

  6. #6
    Registered User
    Join Date
    May 2011
    Location
    Around 8.3 light-minutes from the Sun
    Posts
    1,949
    Ok, so let's at least get you going in the right direction. Take a look at the following skeleton and see how you can apply this to your problem:
    Code:
    #include <iostream>
    #include <bitset>
    
    int main(void){
    
    	std::bitset<32>num1, num2, result;//sets up a 32bit binary container
    	bool carry = false; //use this for your carry flag
    
    	std::cout<<"Enter two binary numbers:";
    	std::cin >> num1 >> num2;
    
    	std::cout <<"You entered: "<<num1.to_string()<<" "<<num2.to_string()<<std::endl;
    	
    	/*now iterate through the bitset and apply your logic
    	for binary addition*/
    
    	std::cout <<"Result: " << result.to_string();
    
    	return(0);
    }
    Quote Originally Posted by anduril462 View Post
    Now, please, for the love of all things good and holy, think about what you're doing! Don't just run around willy-nilly, coding like a drunk two-year-old....
    Quote Originally Posted by quzah View Post
    ..... Just don't be surprised when I say you aren't using standard C anymore, and as such,are off in your own little universe that I will completely disregard.
    Warning: Some or all of my posted code may be non-standard and as such should not be used and in no case looked at.

  7. #7
    Registered User
    Join Date
    Mar 2009
    Posts
    344
    For one thing, you're never using the values you assign to a[] & b[]. And you're doing mod and divide backwards in that loop. And come to think of it, you're using i to set the array bounds before i is initialized - make the definition of a[] and b[] match the one for c[].

    Once you get past that, I think you'll have problems because atoi assumes the string you pass in is a decimal value. You can look at using strtoul instead. Or you can skip this and just convert directly from argv[0][i] and argv[1][i] in your loops which load up a[] & b[].

    Finally, look into ways to simplify the if/else sequence. You're adding numbers, so add a[i], b[i] & carry_in. At most you'll have 3 (1 in both the 1s and 2s places). c[i] == the 1s place, and carry out == the 2s place. Should only be a few lines using one mod and a divide or (or the equivalent bitwise ops) instead of 40-50 lines.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. c++ : binary addition
    By Soul in forum C++ Programming
    Replies: 35
    Last Post: 05-25-2011, 06:53 AM
  2. Replies: 4
    Last Post: 10-08-2010, 01:30 PM
  3. need some help with binary addition.
    By InvariantLoop in forum C++ Programming
    Replies: 21
    Last Post: 01-27-2005, 06:52 AM
  4. saturated binary/hex addition
    By revelation437 in forum A Brief History of Cprogramming.com
    Replies: 13
    Last Post: 03-09-2004, 06:11 PM
  5. Binary tree addition
    By crag2804 in forum C Programming
    Replies: 2
    Last Post: 09-30-2002, 07:48 AM

Tags for this Thread