How to Convert unsigned char* to std::string in C++?

Unicorn picture Unicorn · Nov 4, 2009 · Viewed 117k times · Source

I have unsigned char*, want to convert it to std::string. Can you please tell me the safest way to do this?

Answer

Yacoby picture Yacoby · Nov 4, 2009

You just needed to cast the unsigned char into a char as the string class doesn't have a constructor that accepts unsigned char:

unsigned char* uc;
std::string s( reinterpret_cast< char const* >(uc) ) ;

However, you will need to use the length argument in the constructor if your byte array contains nulls, as if you don't, only part of the array will end up in the string (the array up to the first null)

size_t len;
unsigned char* uc;
std::string s( reinterpret_cast<char const*>(uc), len ) ;