Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 680
Unicorn Avatar asked Nov 04 '09 12:11

Unicorn


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 set a string to a char * C++?

You can't really "assign a string" to a char * , because although a char* parameter is sometimes referred to as a "string parameter", it isn't actually a string, it's a pointer (to a string).

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.


1 Answers

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 ) ; 
like image 114
Yacoby Avatar answered Oct 10 '22 02:10

Yacoby