Copying non null-terminated unsigned char array to std::string Copying non null-terminated unsigned char array to std::string arrays arrays

Copying non null-terminated unsigned char array to std::string


std::string has a constructor that takes a pair of iterators and unsigned char can be converted (in an implementation defined manner) to char so this works. There is no need for a reinterpret_cast.

unsigned char u_array[4] = { 'a', 's', 'd', 'f' };#include <string>#include <iostream>#include <ostream>int main(){    std::string str( u_array, u_array + sizeof u_array / sizeof u_array[0] );    std::cout << str << std::endl;    return 0;}

Of course an "array size" template function is more robust than the sizeof calculation.


Well, apparently std::string has a constructor that could be used in this case:

std::string str(reinterpret_cast<char*>(u_array), 4);


When constructing a string without specifying its size, constructor will iterate over a a character array and look for null-terminator, which is '\0' character. If you don't have that character, you have to specify length explicitly, for example:

// --*-- C++ --*--#include <string>#include <iostream>intmain (){    unsigned char u_array[4] = { 'a', 's', 'd', 'f' };    std::string str (reinterpret_cast<const char *> (u_array),                     sizeof (u_array) / sizeof (u_array[0]));    std::cout << "-> " << str << std::endl;}