Thread: need some help with binary addition.

  1. #1
    Registered User
    Join Date
    Mar 2004
    Posts
    494

    need some help with binary addition.

    can someone help me with binary addition? i know how it works on paper but when it comes to actually coding it, i cant seem to get it as the addition gives the result of regular addition. for example i know the following
    0+0=0
    1+0=1
    1+1=10 , 1 is carried and 0 is placed.

    now when i have 110 + 111 it gives me 221.

    what i was thinking of doing is replace the numbers, for example if the last number is 0 and the last number of the second number is 1 then the output is 1. so i would use some if statements, but if doing this then i will have to use some sort of array or something which confuses me and i have no idea how to get past that problem. any suggestions of what i could do?
    When no one helps you out. Call google();

  2. #2
    Registered User
    Join Date
    Mar 2004
    Posts
    494
    come on any suggestions? i found another method which works in part but its not totally correct someone help me find the error? here is what i have so far.

    Code:
    #include <iostream>
    #include <string>
    using namespace std;
    
    
    
    
    int main()
    {
        string bin1= "1";
            
        string bin2= "0";
            
        string bin3; 
            
        cout << "Enter the 1st binay number: ";
        cin >> bin1;
    
        cout << "Enter the 2nd binary number: ";
        cin >> bin2;
    
        
        bin3 = bin1 + bin2; 
           
    
        cout << "\nfirst number: " << bin1 <<  " Second number: " << bin2 <<  "Result: "<< bin3 <<endl;
    
        return 0;
    }
    edit: nm what i posted, i still need help to figure out the bug on here
    Last edited by InvariantLoop; 01-26-2005 at 05:28 PM.
    When no one helps you out. Call google();

  3. #3
    Registered User axon's Avatar
    Join Date
    Feb 2003
    Posts
    2,572
    first, don't bump posts, second, why are you using strings to hold your values??

    One idea is to convert the binary inputs into decimal; add them; convert back to binary. If you don't know how to convert, do a search on these boards.

    edit:: you could also look here for the basics of binary addition.
    Last edited by axon; 01-26-2005 at 05:34 PM.

    some entropy with that sink? entropysink.com

    there are two cardinal sins from which all others spring: Impatience and Laziness. - franz kafka

  4. #4
    Registered User
    Join Date
    Mar 2004
    Posts
    494
    well doing all those conversions will take time and im looking for the most efficient way to do it.
    When no one helps you out. Call google();

  5. #5
    Registered User axon's Avatar
    Join Date
    Feb 2003
    Posts
    2,572
    first learn how to do it, then work on efficiency. If you say you could do it on paper, it should be a breeze to emulate it through code.

    some entropy with that sink? entropysink.com

    there are two cardinal sins from which all others spring: Impatience and Laziness. - franz kafka

  6. #6
    Registered User
    Join Date
    Mar 2004
    Posts
    494
    its isnt as easy because i cant figure out how to get 1+1=0 with a carry of 1
    When no one helps you out. Call google();

  7. #7
    Hardware Engineer
    Join Date
    Sep 2001
    Posts
    1,398

    strtoul() & <bitset>

    All the data in your computer is already in binary. So, conversion is getting done all the time. Usually it's a default conversion between decimal and binary.

    This means that conversion is done ONLY during input/output. You can input one number in hex, input another in octal, add them together, and display the result in decimal. You don't have to worry about mixing bases, as long as everything is stored as regular integers.

    You can use strtoul() to input a binary number, and <bitset> to display a binary number. Or, if you have a Microsoft compiler, you can use the non-standard itoa() to display binary.

    If you want to do it yourself, I'd suggest that you write the code to do hex-binary conversion, because cin and cout can automatically handle hex. And, hex-binary conversions are easy... you can do them in your head!

    Here's an example program I wrote a couple of years ago:

  8. #8
    Registered User
    Join Date
    Mar 2004
    Posts
    494
    thanks for your suggestion and the tutorial but im still having problems, this is only a binary addition, so the user will only enter 0 and 1's which will have to be added. there shouldn't b conversion of the numbers as it will create problems, the add function should add these numbers and output the binary with no conversions made, conversion is not the point. the main point of this is efficiency, and you can achieve that by finding a way to make the program think that 1+ 1 =0 with a carry of 1. maybe i can make use of logical operators and bitwise operators so that i can get the addition to work
    When no one helps you out. Call google();

  9. #9
    UT2004 Addict Kleid-0's Avatar
    Join Date
    Dec 2004
    Posts
    656
    This code is a failure and will not work, but enjoy trying to get it to work, as I cannot...
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    // Allow boolean types
    typedef enum
    {
      false,
      true
    } bool;
    
    // Add binary numbers and return binary
    int addBinary (int b1, int b2);
    
    int main (void)
    {
      // Binary numbers b1 and b2 get added together
      int b1 = 111, b2 = 101;
      // Binary addition answer
      int b3;
    
      // Add binary numbers
      b3 = addBinary (b1, b2);
    
      // Print out binary addition
      printf ("111 + 101 = %d\n", b3);
    
      return 0;
    }
    
    // Add binary numbers and return binary
    int addBinary (
        int b1,     // The first binary number
        int b2)     // The second binary number
    {
       // The binary addition answer, transforms into binary.
       int a;
       // Carrier for binary addition
       bool carrier = false;
       // Current digit step (starts at 1)
       int s = 2;
    
       // Add the numbers like decimal
       a = b1 + b2;
    
    // Next Binary digit
    NBD:
        // If the carrier is true, add one to the current placement
        if (carrier)
        {
          a += 1 * (s - (s / 2));
          carrier = false;
        }
    
        // If the carrier makes the postdigit a 3, we have trouble
        if (a % (s / 2 + s) < s / 2)
        {
          a += 1 * ((s * 10) - ((s * 10) / 2));
          a -= 1 * (s - (s / 2));
        }
    
        // If the addition yields a 2 * digit placement,
        // remove it and set carrier binary addition to true.
        if (a % s < (s / 2))
        {
          a -= 1 * (s - (s / 2));
          carrier = true;
        }
    
        // If our digit placement is high enough, exit
        if (s > a)
          return a;
    
        // Set the digit placement higher
        s *= 10;
    
        // Verify next placement (Next binary Digit)
        goto NBD;
    }
    Last edited by Kleid-0; 01-26-2005 at 11:14 PM.

  10. #10
    Registered User
    Join Date
    Mar 2004
    Posts
    494
    thanks for the compliment lol, i guess.. ive been studying C and C++on my own recently and today ive been infront of the monitor from 11am.

    anyway back to the matter at hand, im getting a few errors when i try to compile your code.
    Code:
    C:\Program Files\Microsoft Visual Studio\MyProjects\proj\ver3.cpp(7) : error C2059: syntax error : 'constant'
    C:\Program Files\Microsoft Visual Studio\MyProjects\proj\ver3.cpp(9) : error C2143: syntax error : missing ';' before '}'
    C:\Program Files\Microsoft Visual Studio\MyProjects\proj\ver3.cpp(9) : error C2143: syntax error : missing ';' before '}'
    Error executing cl.exe.
    
    ver3.exe - 3 error(s), 0 warning(s)
    When no one helps you out. Call google();

  11. #11
    Registered User axon's Avatar
    Join Date
    Feb 2003
    Posts
    2,572
    > thanks for the compliment lol

    I doubt that was a compliment for you - you have not shown any effort in order to solve this problem.

    > anyway back to the matter at hand, im getting a few errors when i try to compile your code.

    I don't think erasing that whole typedef will change anything. Try deleting it and see if that'll work

    some entropy with that sink? entropysink.com

    there are two cardinal sins from which all others spring: Impatience and Laziness. - franz kafka

  12. #12
    Registered User
    Join Date
    Mar 2004
    Posts
    494
    well if it wasnt referred to me, i take it back. sorry if i offened anyone but problems dont have only 1 solution and im trying to find 1 of the soultions which is more relevant at what im trying to achieve, and i beleive im on the right track.
    When no one helps you out. Call google();

  13. #13
    UT2004 Addict Kleid-0's Avatar
    Join Date
    Dec 2004
    Posts
    656
    My bad I was using C with C++ comments lol. Delete the whole typedef struct at the top, because its type is bool and there is already a type bool in C++.

    This is not valid in C++:
    Code:
    #include <stdio.h>
    #incude <stdlib.h>
    Change that to:
    Code:
    #include <iostream>
    And then change:
    Code:
    // Print out binary addition
    printf ("111 + 101 = %d\n", b3);
    To This:
    Code:
    // Print out binary addition
    cout << "111 + 101 = " << b3 << endl;
    Add this to the top of the file after the #includes:
    Code:
    using std::cout;
    using std::endl;

  14. #14
    Registered User Scribbler's Avatar
    Join Date
    Sep 2004
    Location
    Aurora CO
    Posts
    266
    Wow what a confusing mess. This would all be easier if you simply outlined the program in pseudocode, or flowchart it if you prefer. That's what I do the moment I realize I'm stuck in the logic to a solution. You'll find you'll get the solution so much quicker that way.

    Here's a sample...
    Code:
    Initialize variables
        Int digit1, digit2    // Digits to be summed //
        Int num1, num2     // User Input //
        Int dsum            // sum of digit1 and digit2 //
        Int carrier = 0        // Initialize the carrier to 0 //
        
    While value exists for num1 or num2 or carrier
        Strip Digit from each number 
            digit1 = num1 % 10
            digit2 = num2 % 10
            num1 = num1 / 10
            num2 = num2 / 10
        Add 2 digits
            digit1 + digit2 + carrier = dsum
            if dsum == 2
                dsum = 0
                carrier = 1
            else if dsum == 3
                dsum = 1
                carrier =1
            else
                carrier = 0
        Store dsum        // Store the final digit for later retreival //
    
    Output stored digits
    That's off the top of my head, so I didn't bother to take time to incorporate a method of storing the digits (a simple array should suffice or an algorithm to sum it into an integer).

    Oh, and PUHLEAZE tell me I didn't scan through this thread and actually see a GOTO statement. :P
    Last edited by Scribbler; 01-26-2005 at 09:35 PM.

  15. #15
    UT2004 Addict Kleid-0's Avatar
    Join Date
    Dec 2004
    Posts
    656
    Hey Scribbler my Linux friend lol. Yes, you did see a goto, and I should be slapped. I'm trying to do this cool pretty code code structure, and to keep the indentation to the left, I felt the only way at the time was to use the goto. I'm so sorry, I'm a failure!!!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 0
    Last Post: 11-04-2006, 11:07 AM
  2. Binary Search Trees Part III
    By Prelude in forum A Brief History of Cprogramming.com
    Replies: 16
    Last Post: 10-02-2004, 03:00 PM
  3. Tutorial review
    By Prelude in forum A Brief History of Cprogramming.com
    Replies: 11
    Last Post: 03-22-2004, 09:40 PM
  4. Request for comments
    By Prelude in forum A Brief History of Cprogramming.com
    Replies: 15
    Last Post: 01-02-2004, 10:33 AM
  5. Binary tree addition
    By crag2804 in forum C Programming
    Replies: 2
    Last Post: 09-30-2002, 07:48 AM