c++type-conversioncpu-wordnibble

Unable to extract nibbles out of a word


I am trying to extract 4-bits from a 16-bit binary string, i.e nibbles out of a word Can anyone tell me what is wrong with this program?

#include <sstream>
#include <iomanip>
#include <math.h>
#include<iostream>

using namespace std;

int main()
{
    std::string aBinaryIPAddress = "1100110011001100";

    std::string digit0 = aBinaryIPAddress & 0x0f;
    cout << "digit0 : " << digit0 << endl;

    std::string digit1 = (aBinaryIPAddress >>  4) 0x0f;
    cout << "digit1 : " << digit1 << endl;

    std::string digit2 = (aBinaryIPAddress >>  8) 0x0f;
    cout << "digit2 : " << digit2 << endl;

    std::string digit3 = (aBinaryIPAddress >> 12) 0x0f;
    cout << "digit3 : " << digit3 << endl;

    return 0;
}

I am getting the following error:

 changes.cpp: In function `int main()':
 changes.cpp:117: error: invalid operands of types `char*' and `int' to binary `
 operator>>'
 changes.cpp:117: error: parse error before numeric constant

Solution

  • If you are manipulating a string, you should be using substr, not "shift and mask" technique: & and >> operators are undefined for strings and ints.

    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
    

    Demo on ideone.

    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);