1

I have an std::array and I want to create a string from it by converting each byte to its equal HEX value something like this:

 string getString(array<unsigned char, 10> data)
 {
     // what is the faster way to do this?
 } 

main()
{
    array<unsigned char, 10> data={0,1,2,3,4,5,6,7,8,9};

   string result=getString(data);
   out<<result<<endl;
}

and it should print something such as:

0x00 0x01 0x02 0x03

or even

00010203040506070809

any way that is faster.

I know that I can use a for loop and do this job, but if there any neater way to do this?

DeiDei
  • 10,205
  • 6
  • 55
  • 80
mans
  • 17,104
  • 45
  • 172
  • 321

2 Answers2

1

you can do something like below

string getString(array<unsigned char, 10> data)
{
   std::stringstream ss;
   ss << std::hex << std::setfill('0');
   for(int i=0; i<data.size(); ++i)
      ss << std::setw(2) << (int)data[i];
   return ss.str();
} 
Maddy
  • 774
  • 5
  • 14
  • You could use a range-for to make the purpose of the loop more immediately obvious, e.g., `for (const auto& c : data)` and then use `c` in place of `data[i]` – Frank Boyne May 23 '18 at 16:18
  • It can be done. We could even make use of std:for_each STL function – Maddy May 23 '18 at 16:21
  • Certainly `std::for_each` would also work. In a case like this I think the extra complexity of creating a lambda or function to apply to each element would make the code less readable? – Frank Boyne May 23 '18 at 16:51
1

If you want to have a bit of fun, you can use an std::ostream_iterator:

template<class Container>
std::string hex(Container const& c)
{
    std::stringstream out;
    std::copy(begin(c), end(c), std::ostream_iterator<unsigned int>(out << std::hex, " "));
    return out.str();
}

Usage

std::cout << hex(array) << "\n";

Demo

http://coliru.stacked-crooked.com/a/9bc542742b1566e2

YSC
  • 38,212
  • 9
  • 96
  • 149