I have unsigned char*
, want to convert it to std::string
. Can you please tell me the safest way to do this?
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.
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.
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).
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.
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 ) ;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With