Search code examples
c++binaryhexstrtol

How to return a hex value after converting it from a string


I am trying to return a hex value inside this method. not sure where I'm going wrong. not sure how put the value into hex without using cout. have not been able to find a solution. Input value is always going to be 32 bits long

its like i want to return hex << x but thats not an option.

string StringToHex (myInstruction* RealList, int Pos)
{
    string result = "11111111110000000000110011001100";
    unsigned long x = strtoul(result.c_str(), &pEnd, 2);
    cout<< hex << x<<endl;
    return  x;
}

Solution

  • You can use a stringstream instead of cout.

    cout is just one special ostream that is created by default and is hooked up to the program's standard output. You can create other ostream objects that write to different things. std::stringstream writes to a std::string inside it.

    #include <sstream>
    
    std::string to_hex() {
      unsigned int x = 256;
    
      std::stringstream s;
      s << std::hex << x;
      return s.str();
    }