Search code examples
c++stringtype-conversionunsigned-char

C++ conversion from unsigned char to std::string


Intro: Consider that I have no experience with C++, but can find my way around any language to do basic tasks. Most of my experience is with .net languages (vn.net and C#), php and js, so please explain as if you were teaching a complete noob.

Here is the problem: I receive data in an unsigned char characters[12]; and I have to then append that data to a std::string

data is always 12 characters long, and is not null terminated, because it is gathered by selecting specific bytes received from serial port.

Long story short:

std::string stroutput = "some text ";
unsigned char characters[12];
characters[0]=64; //demo data to shorten the code
characters[1]=72;
stroutput.append(characters[0]);
stroutput.append(characters[1]);
....

The result i want is to have the string value

some text @H...

But what i get is an error while compiling

error: invalid conversion from ‘unsigned char’ to ‘const char*’ [-fpermissive]
stroutput.append(characters[0]);
                 ~~~~~~~~~~~~^

Logic behind this thinking is that output of:

printf("%c%c",characters[0],characters[1]);

and

std::cout << characters[0] << characters[0] << std::endl;

results in

@H

So: How do I convert unsigned char something[12] to std::string?

Thanks

Edit: Sorry for the duplicate, search didn't return that question. Thanks everyone - too bad I can't mark multiple answers!


Solution

  • To append a character you have to use the following overloaded method append

    basic_string& append(size_type n, charT c);
    

    For example

    stroutput.append(1, characters[0]);
    stroutput.append(1, characters[1]);
    

    Otherwise use method push_back or the operator +=. For example

    stroutput += characters[0];
    stroutput += characters[1];
    

    If you want to append the whole array or its part then you can write

    stroutput.append( reinterpret_cast<char *>( characters ), sizeof( characters ) );
    
    stroutput.append( reinterpret_cast<char *>( characters ), n );
    

    where n is the number of characters of the array to append.