1

I'm using this code to convert the unsigned char* (points to an array of 256 values) to std::string:

int ClassA::Func(unsigned char *dataToSend, int sendLength)
{
    std::stringstream convertStream;
    std::string dataToSendStr = "";

    for(int i=0; i<=sendLength; i++) convertStream << dataToSend[i];    

    while(!convertStream.eof()) convertStream >> dataToSendStr;
    ...
}

but then I have dataToSendStr in this format:

dataToSendStr "" 
[0]           0x00 
[1]           0x00 
[2]           0x04 
[3]           0xC0

if I now use this value I only get "" and not the important values [0-3]!

-> need something like: dataToSendStr "000004C0"

Thx for your help!

2
  • As an aside, you don't have to use the for() ... construct to write the elements to a stream. You can use copy( dataToSend, dataToSend+sendLength, ostream_iterator<string>(convertStream) ); if you want to avoid hand-written loops. Commented Nov 15, 2012 at 14:21
  • When you say "need something like", did you actually mean "this is the exact string I want given this input"? Commented Nov 15, 2012 at 14:24

1 Answer 1

6

Use the IO manipulator std::hex if you want (which is what I think based on the need something like part of the question) a hexadecimal representation of the characters in dataToSend:

std::ostringstream convertStream;
convertStream << std::hex << std::setfill('0');

for (int i = 0; i < sendLength; i++)
{
    convertStream << std::setw(2) << static_cast<short>(dataToSend[i]);
}
Sign up to request clarification or add additional context in comments.

Comments

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.