Question: 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.

Answer: 
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](https://en.wikipedia.org/wiki/Logical_shift) `<<`, to move the binary bits, when you go right in the ascii string;
* [binary or](https://en.wikipedia.org/wiki/Bitwise_operation) `|` for setting the bits.
```
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;
}

```