sarath
sarath

Reputation: 543

Encode std::string with hex values

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.

Upvotes: 1

Views: 2333

Answers (1)

Mike Seymour
Mike Seymour

Reputation: 254431

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

Upvotes: 5

Related Questions