9

Possible Duplicate:
How to Convert Byte* to std::string in C++?

I'm on an embedded device and try to receive a message. This message is given by a const uint8_t* data and its length size_t len.

Now I need a std::string to output my data.

Ciro Santilli OurBigBook.com
  • 347,512
  • 102
  • 1,199
  • 985
Lincoln
  • 744
  • 1
  • 7
  • 20

3 Answers3

16

If you don't want to convert the encoding, this will work:

std::string s( data, data+len );

If you want to convert UTF-8 into whatever system encoding is used by your platform, you need to use some platform-specific means.

sbi
  • 219,715
  • 46
  • 258
  • 445
1

Is your uint8* string null-terminated? If so, you can just do:

std::string mystring(data);
Oliver Charlesworth
  • 267,707
  • 33
  • 569
  • 680
  • when there's a length, the data is probably not null-terminated – Milan Dec 22 '10 at 12:08
  • And it's probably better to explicitly specify it anyway; all that's going to do is search for the length again anyway. – GManNickG Dec 22 '10 at 12:58
  • Also you are assuming that there is no '\0' character inbedded in the string. The std::string does not put any special emphasis on the '\0' character. – Martin York Dec 22 '10 at 19:56
0

For some case sizeof(uint8) != sizeof(char), you could do:

std::string output( len, 0 );
for ( size_t i = 0; i < len; ++i )
  output[ i ] = static_cast<char>( data[ i ] );
Flinsch
  • 4,296
  • 1
  • 20
  • 29
  • 3
    `sizeof(uint8)!=sizeof(char)` is impossible. `sizeof` is in units of `char`, so if `char` is larger than 8 bits, there is no way to have an 8-bit type, i.e. `uint8` cannot exist. – R.. GitHub STOP HELPING ICE Dec 22 '10 at 16:13