How do I convert an 'unsigned char' to 'string'

Oct 4, 2014 at 9:58pm
Hi there, how do I convert a variable of type unsigned char to string. thanks
Oct 4, 2014 at 10:02pm
Do you want a string containing a single character?
1
2
unsigned char uc = /*...*/;
std::string s(1, static_cast<char>(uc));
Oct 4, 2014 at 10:05pm
thank for your reply. I want a string containing a max of 256 characters
Oct 4, 2014 at 10:12pm
containing a max of 256 characters
do I convert a variable of type unsigned char to string
How would you convert a single character to the several? Describe what you have and what are you want to achieve. Preferrably with examples.
Oct 4, 2014 at 10:23pm
OK, I have a variable of type unsigned char; this variable contains a once word string. So I want to convert this variable from the type unsigned char to std::string please see the example below.

unsigned char myVar[10] = "abcdefg"

I want to convert the variable above to type std::string.
Oct 4, 2014 at 10:31pm
You have array, not a single char.

1
2
3
4
5
6
7
8
9
#include <string>
#include <iostream>

int main()
{
    unsigned char myVar[10] = "abcdefg";
    std::string res(myVar, myVar + 7);
    std::cout << res;
}

Oct 5, 2014 at 8:05pm
that doesn't work either.
Oct 5, 2014 at 8:13pm
Oct 5, 2014 at 8:50pm
could it have anything to do with the fact that the variable i am trying to convert to string is actually of type uint8_t. I did not disclose this because as far as I know uint8_t is simply a typedef for unsigned char.
Oct 5, 2014 at 8:57pm
Topic archived. No new replies allowed.