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.
Here is the complete code
#include <bits/stdc++.h>
using namespace std;
typedef unsigned char BYTE;
int main() {
//method 1;
std::vector<BYTE> data = {'H','E','L','L','O','1','2','3'};
//string constructor accepts only const char
std::string s((const char*)&(data[0]), data.size());
std::cout << s << std::endl;
//method 2
std::string s2(data.begin(),data.end());
std::cout << s2 << std::endl;
//method 3
std::string s3(reinterpret_cast<char const*>(&data[0]), data.size()) ;
std::cout << s3 << std::endl;
return 0;
}
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 );
If has access to CryptoPP
Readable Hex String to unsigned char
std::string& hexed = "C23412341324AB";
uint8_t buffer[64] = {0};
StringSource ssk(hexed, true,
new HexDecoder(new ArraySink(buffer,sizeof(buffer))));
And back
std::string hexed;
uint8_t val[32] = {0};
StringSource ss(val, sizeof(val), true,new HexEncoder(new StringSink(hexed));
// val == buffer
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;
Source: Stackoverflow.com