If you are manipulating a string
, you should be using substr
, not "shift and mask" technique: &
and >>
operators are undefined for strings and int
s.
Here is how to do it with substr
:
#include <iostream>
#include <string>
using namespace std;
int main() {
string aBinaryIPAddress = "0101100111101101";
size_t len = aBinaryIPAddress.size();
for (int i = 0 ; i != 4 ; i++) {
cout << "Digit " << i << ": " << aBinaryIPAddress.substr(len-4*(i+1), 4) << endl;
}
return 0;
}
This prints
Digit 0: 1101
Digit 1: 1110
Digit 2: 1001
Digit 3: 0101
If you need four individual variables, "unroll" the loop, like this:
string d0 = aBinaryIPAddress.substr(len-4, 4);
string d1 = aBinaryIPAddress.substr(len-8, 4);
string d2 = aBinaryIPAddress.substr(len-12, 4);
string d3 = aBinaryIPAddress.substr(len-16, 4);