Question:
C++ simple program help!?
Jason
2013-11-25 23:32:14 UTC
There's a question on my homework assignment asking me to have someone put a string of 8 zero and ones as a binary number.
I'm then suppose to convert that binary integer into it's base 10 representation, so pretty much binary to decimal.

So far all I managed to get down is have user input the string and store it as an array. I know the formula would be something like
sum += (pow(2,j) * arr[i])
Any help would be much appreciated, thanks!
Three answers:
2013-11-25 23:55:23 UTC
First off, do you know how to calculate a base 10 integer from a binary string? (That's where you start.) You go through the binary string, look for the zero or ones, and raise 2 to the ith power if a 1 is present, where i is the loop iteration between 0 and 7 (Remember integers are represented as 2^(n-1) - 1 (- 1 from the power to include negative numbers, - 1 from total number to include 0).



So with a bit of psuedocode:

int i = 0, num = 0;

char bin[8] = '01010101';



for(i from 0 to 7 incrementing by 1)

---if bin[i] == '1'

------num += Math.pow(2, i);

---else if bin[i] == '0'

------continue loop; //handle cases where user enters something other than 0 or 1



print num;



Try to code this on your own. It's not that difficult and there are many solutions. Post your code here if you get stuck. Good luck and have fun.
cja
2013-11-26 18:02:40 UTC
Jonathan's answer and algorithm are good: you don't need pow, just shift bits into place. Here's another way to do it (and I always recommend including user input validation):



#include

#include

#include

#include



using namespace std;



bool isValidBinaryStr(const string&);

int str2bin(const char *);

const size_t bitsPerInt = sizeof(int) * CHAR_BIT;



int main(int argc, char *argv[]) {

    string in;



    while (true) {

        cout << endl << "Enter up to " << bitsPerInt << " 1s and 0s: ";

        getline(cin,in);

        if ((in.size() > 0) && (in.size() <= bitsPerInt) && (isValidBinaryStr(in) == true)) {

            cout << str2bin(in.c_str()) << endl;

        }

    }

    return 0;

}



//

// Convert string of bits to an integer

//

int str2bin(const char *s) {

    if (*s == '\0') return 0;

    return ((*s - '0') << ((strchr(s, '\0') - s) - 1)) | str2bin(s + 1);

}





//

// Return true if all characters of s are either '1' or '0'.

//

bool isValidBinaryStr(const string &s) {

    string::const_iterator i;

    bool valid = true;



    for (i = s.begin(); (i != s.end()) && (valid == true); i++) {

        valid = ((*i == '1') || (*i == '0'));

    }

    return valid;

}





#if 0



Sample run:



Enter up to 32 1s and 0s: 10

2



Enter up to 32 1s and 0s: 1111

15



Enter up to 32 1s and 0s: 101001110010

2674



Enter up to 32 1s and 0s: 11010110

214



Enter up to 32 1s and 0s: 11111111111111111111111111111111

-1



#endif
Jonathan
2013-11-26 08:41:33 UTC
Try something like the following. No need for the pow() function:



#include

#include

using namespace std;

int main( ) {

    string q;

    while ( getline( cin, q ) && !q.empty( ) ) {

        unsigned int result= 0;

        const string::size_type len= q.size();

        for ( string::size_type i= 0; i < len; ++i ) {

            result <<= 1;

            if ( q[i] == '1' ) ++result;

        }

        cout << result << endl;

    }

    return 0;

}



The above uses one of several pre-C++11 style approaches to looping over strings. And it assumes every character is a 0 unless it is exactly a 1. You could add error checking if you want that.


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Continue reading on narkive:
Loading...