0

I am writing a program where the input data (in binary) is split into half and convert to integer to perform some calculation. So I:

  1. Accept binary input and store as "String"

  2. Split string (note: to be treated as binary) into half and convert to int and store in x and y

So far i have written step 1.

int main() {
    string input;
    cout << "Enter data:";
    getline(cin, input);

    int n = input.size();
    int n1 = n/2;

    string a, b;
    a = input.substr(0,n1);
    b = input.substr(n1);

    cout << "a: " << a;
    cout << "b: " << b;
}

Would like to know how to achieve step 2. Thanks in advance.

6
  • cplusplus.com/reference/cstdlib/atoi Commented Jul 26, 2015 at 17:22
  • 1
    @Nolane How is your comment relevant? Question was about binary format, while atoi "[...] takes an optional initial plus or minus sign followed by as many base-10 digits [...]". As to the question - we don't solve homeworks here. Read this: en.wikipedia.org/wiki/Binary_number#Decimal and then implement. It is one of the most basic algorithms in CS. Commented Jul 26, 2015 at 17:28
  • Homework related questions are fine as long as you're not simply asking us to complete a step for you. Just re-factor your question to ask more specifically what about step 2 your having problems with and make sure you include things you've tried so far. Commented Jul 26, 2015 at 18:11
  • 1
    @DanBeaulieu this is not homework. i am just trying out something and yes i will do this on my own. In no way asking anyone to provide the complete code easily to me. Commented Jul 26, 2015 at 18:15
  • @MateuszGrzejek Thanks for the link. I'm trying to implement. Commented Jul 26, 2015 at 18:16

2 Answers 2

2

You can try this:

if(a.length() <= sizeof(unsigned int) * 8) {
    unsigned x = 0; 
    for(int i = 0; i < a.length(); i++) {
        x <<= 1;  // shift byt 1 to the right
        if(a[i] == '1')
            x |= 1; // set the bit
        else if(a[i] != '0') {
            cout << "Attention: Invalid input: " << a[i] << endl; 
            break; 
        }
    }
    cout << "Result is " << x << endl; 
}
else cout << "Input too long for an int" << endl; 

It uses

  • shift left <<, to move the binary bits, when you go right in the ascii string;
  • binary or | for setting the bits.
Sign up to request clarification or add additional context in comments.

Comments

0
int bin2dec(char* str) {
 int n = 0;
 int size = strlen(str) - 1;
        int count = 0;
 while ( *str != '\0' ) {
  if ( *str == '1' ) 
      n = n + pow(2, size - count );
  count++; 
  str++;
 }
 return n;
}

int main() {
 char* bin_str = "1100100";
 cout << bin2dec(bin_str) << endl;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.