Question

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;
}
Was it helpful?

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

OTHER TIPS

Use std::stringstream

std::stringstream ss;
ss<< std::hex << x;
std::string res= ss.str();

If I understand your questinon, you want to return a hex value as a string, rigt? If so, then:

std::string intToHexStr (int val)
{
    std::stringstream sstr;
    sstr << hex << val;
    std::string result;
    sstr >> result;
    return result;
}

Hope this helps!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top