Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

convert unsigned char* to std::string

I am little poor in typecasting. I have a string in xmlChar* (which is unsigned char*), I want to convert this unsigned char to a std::string type.

xmlChar* name = "Some data";

I tried my best to typecast , but I couldn't find a way to convert it.

like image 558
Cyril Avatar asked Jul 19 '13 12:07

Cyril


People also ask

Should I use std :: string or * char?

Use std::string when you need to store a value. Use const char * when you want maximum flexibility, as almost everything can be easily converted to or from one.

How do I turn an unsigned int into a string?

The utoa() function coverts the unsigned integer n into a character string. The string is placed in the buffer passed, which must be large enough to hold the output. The radix values can be OCTAL, DECIMAL, or HEX.

Can you cast unsigned char to char?

You can pass a pointer to a different kind of char , but you may need to explicitly cast it. The pointers are guaranteed to be the same size and the same values.

What is unsigned char pointer?

unsigned char is the smallest unsigned integral type, and may be used when manipulating arrays of small values on which bitwise operations are used.


1 Answers

std::string sName(reinterpret_cast<char*>(name));

reinterpret_cast<char*>(name) casts from unsigned char* to char* in an unsafe way but that's the one which should be used here. Then you call the ordinary constructor of std::string.

You could also do it C-style (not recommended):

std::string sName((char*) name);
like image 107
sasha.sochka Avatar answered Sep 30 '22 02:09

sasha.sochka