Convert unsigned char to String

Hi there,

I’m having some trouble trying to convert an unsigned char to a string.
I’m trying to covert dta into a string. Thanks in advance for any help

int len = 0;
unsigned char dta[20];
   dta[len++] =;
//convert dta into a string here

Some clarification is needed her.

If you are looking for a way to make your char array a C string, you should just add dta[len] = '\0'; after your while loop.
You’d have to do this anyway, even for the next step.
If youn want a String object, than you just need to assign the char array to your String object like this myStringObj = dta;.

In addition you have to make sure, that your while() {} never fills more than 19 characters into your char array, since you need to leave space for the zero-terminator.


Thanks for the reply. I’ve added the cpp data[len]='\0'; now (thanks)

Using cpp String myStringObj = dta gives me the following error:

invalid conversion from 'unsigned char*' to 'const char*'

I’ve played around a bit more and I’ve got the following working:

        String myString = "";
        for(int x = 0; x < len-1; x++)
            myString = myString +String(char(dta[x]));

Is there a more elegant way to produce the same result?

Your error message gives you the clue already.
The assign operator = for the String object expects a different type to what you (or I in this case :wink: ) supplied. But since both types are compatible you just need to type cast it like this

myString = (const char*)dta;

Thanks for your help @ScruffR