Search code examples
c++binaryhexstrtol

How to do a true strtoul? Wont intake an actual string


Having an issue inputting an ACTUAL string to strtuol. The input string SHOULD be an unsigned binary value of 32 bits long.

Obviously, there is in issue with InputString = apple; but I'm not sure how to resolve the issue. any thoughts? This shouldnt be that difficult. not sure why I'm having such a hard time with it.

Thanks guys.

#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main()
{
    char InputString[40];
    char *pEnd = NULL;          // Required for strtol()
    string apple = "11111111110000000000101010101000";
    //cout << "Number? ";
    //cin >> InputString;
    InputString = apple;
    unsigned long x = strtoul(InputString, &pEnd, 2);     // String to long

    cout << hex << x << endl;
    return 1;
}

Solution

  • Include :

    #include<cstdlib> // for strtol()
    #include<cstring> // for strncpy()
    

    and then

     strncpy(InputString ,apple.c_str(),40); 
                                ^
                                |
                                convert to C ctring 
    

    Or simply,

    unsigned long x = strtoul(apple.c_str(), &pEnd, 2);