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.

Mike Seymour
  • 249,747
  • 28
  • 448
  • 644
sarath
  • 513
  • 6
  • 18
  • 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` – WhozCraig Mar 11 '14 at 06: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](https://ideone.com/FZuZLu). – WhozCraig Mar 11 '14 at 06:52

1 Answers1

4

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};
Mike Seymour
  • 249,747
  • 28
  • 448
  • 644