views:

387

answers:

4

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

+1  A: 
BYTE *str1 = "Hello World";
std::string str2((char *)str1);  /* construct on the stack */

Alternatively:

std::string *str3 = new std::string((char *)str1); /* construct on the heap */
cout << &str3;
delete str3;
spoulson
Unicorn
That's because `std::string` doesn't have a constructor that takes an `unsigned char*`, and so the compiler falls back on the templated constructor meant for allocators. You need to either use `std::string(Iterator begin, Iterator end)`, or `std::string(const char*, std::size_t n)` and cast the BYTE* to a char*
Charles Salvia
sbk
You're all right. I hadn't run this through the compiler as I should have. You will need the (char *) typecast, since std::string doesn't handle BYTE/unsigned char types. And the reference example was wrong; it should have been a pointer.
spoulson
+2  A: 

BYTE* is probably a typedef for unsigned char*, but I can't say for sure. It would help if you tell us what BYTE is.

If BYTE* is unsigned char*, you can convert it to an std::string using the std::string range constructor, which will take two generic Iterators.

const BYTE* str1 = reinterpret_cast<const BYTE*> ("Hello World");
int len = strlen(reinterpret_cast<const char*>(str1));
std::string str2(str1, str1 + len);

That being said, are you sure this is a good idea? If BYTE is unsigned char it may contain non-ASCII characters, which can include NULLs. This will make strlen give an incorrect length.

Charles Salvia
+1  A: 

BYTE is nothing but typedef unsigned char BYTE;

You can easily use any of below constructors

string ( const char * s, size_t n );
string ( const char * s );
sat
+5  A: 

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 ) ;
Yacoby
BYTE * pbData = "SomeString"size_t length = 10I have the length before hand, so i used this :I used this method, "std::string(reinterpret_cast<char *>(pbData), length );"It works, but once in while i see crash in memcpy.Tryint to find our why crash happened, though it seems working for me
Unicorn
As a portability pedant, I want to point out that this only works on systems with 2's complement arithmetic. On 1's complement or sign-magnitude architectures, it is not safe to reinterpret_cast between `char*` and `unsigned char*` (well, it's safe, but you'll get surprising results if `char` is signed and any of the characters have the top bit set). In this case the questioner is obviously on Windows, so no problem.
Steve Jessop