1

My application requires some hex values to be encoded and transmitted in std::string. So I'm doing like this.

static string printHex(const string& str)
{
    stringstream ss;
    ss << "[ " << hex;
    for (int i = 0; i < str.size(); i++)
    {
        ss << (((uint32_t)str[i] )& 0xFF) << " ";
    }
    ss << "]" << dec;

    return ss.str();
}

int main()
{
    char ptr[] = {0xff, 0x00, 0x4d, 0xff, 0xdd};// <--see here, 0x00 is the issue.
    string str(ptr);
    cout << printHex(str) << endl;
    return 0;
}

Obviously the string is taking values only upto 0x00, the rest of the data is lost. Without 0x00 it'll work for any values. But I need 0x00 also. Please suggest a solution. Thanks for the help.

2
  • Unrelated: Unless your char type is naturally unsigned, I'm somewhat surprised you don't get a warning about 0xDD and 0xFF both being constant expressions that cannot be narrowed to type char Commented Mar 11, 2014 at 6:33
  • 1
    I do something similar to this often for debug dumps of buffers. Fitted with your code, snippets of such impls can be seen here. Commented Mar 11, 2014 at 6:52

1 Answer 1

5

Construct the string from the entire range of the array:

std::string str(std::begin(ptr), std::end(ptr));   // C++11
std::string str(ptr, ptr + sizeof ptr);            // Historical C++

Note that this only works if ptr is actually an array, not a pointer. If you only have a pointer, then there's no way to know the size of the array it points to.

You should consider calling the array something other than ptr, which implies that it might be a pointer.

Alternatively, in C++11, you can list-initialise the string with no need for an array:

std::string str {0xff, 0x00, 0x4d, 0xff, 0xdd};
Sign up to request clarification or add additional context in comments.

1 Comment

Clear enough!! You are awesome Mike.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.