Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to cast tr1/array to std::string?

I wonder how to cast std::tr1::array<unsigned char, 16> to a std::string?

the compiler always complain, I've tried

std::tr1::array<unsigned char, 16> sss;
string(sss);
string asd(sss);

either does work...

like image 819
weeo Avatar asked Mar 23 '23 13:03

weeo


1 Answers

unsigned char makes this tricky. If you know that your system uses 2s complement 1 byte 8 bit unsigned char and char, and implicit conversion from unsigned char to char does what you want (these are not always true!), and your array buffer is null terminated (ie, characters after the first 0 one should be discarded), this function works:

template<std::size_t N>
std::string to_string( std::array<unsigned char, N> const& arr ) {
  std::string retval;
  for( auto c : arr ) {
    if (!c)
      return retval;
    retval.push_back(c);
  }
  return retval;
}

I included some paranoia about the possibility that the array might be "full" and be missing the null terminator.

If you actually want all 16 unsigned char, even if some are null, you'll want to use this:

std::string str( arr.begin(), arr.end() );

which should use implicit conversion from the unsigned char to char.

If implicit casting doesn't do what you want, and you know that the array's memory is actually an array of char even though its type is unsigned char, you need to do some reinterpret-casting.

For the null terminated case:

template<std::size_t N>
std::string to_string_helper( const char* buf ) {
  std::string retval; 
  if (!buf)
    return retval;
  for ( const char* it = buf; it < (buf+N); ++it ) {
    if (!*it)
      return retval;
    retval.push_back(*it);
  }
  return retval;
}
template<std::size_t N>
std::string to_string_2( std::array<unsigned char, N> const& arr ) {
  return to_string_helper<N>( arr.data() );
}

and for the "entire buffer" case:

template<std::size_t N>
std::string to_string_2( std::array<unsigned char, N> const& arr ) {
  const char* str = reinterpret_cast<const char*>(arr.data());
  return std::string( str, str+N );
}
like image 78
Yakk - Adam Nevraumont Avatar answered Apr 02 '23 02:04

Yakk - Adam Nevraumont