Conversion into hexadecimal using C++ I want to read a vector of eight bytes, convert them into hexadecimal, store them in a std::string and finally write them into a binary file.
I am looking for suggestions and recommendations to improve the efficiency and readability of the code.
#include &lt;vector&gt;
#include &lt;string_view&gt;
#include &lt;iostream&gt;
#include &lt;fstream&gt;
#include &lt;cassert&gt;

std::string hexify(std::vector&lt;unsigned char&gt; const &amp; v) {

std::string str(2 * v.size(), 'x');
auto k = str.begin();

for(auto i{v.begin()}; i &lt; v.end(); ++i) {
    *k++ = &quot;0123456789ABCDEF&quot;[*i &gt;&gt; 4];
    *k++ = &quot;0123456789ABCDEF&quot;[*i &amp; 0x0F];
}
return str;

}

void writeFile(std::string_view str, std::string strToRead) {

assert(str.data() != nullptr);
std::ofstream f(str.data(), std::ios::binary);

if(f.is_open()) {
    f &lt;&lt; strToRead;
}
f.close();
}

int main() {

std::vector&lt;unsigned char&gt; const v{'5', '1', '5', '7', '9'};
writeFile(&quot;text.bin&quot;, hexify(v));
}
First off, your formatting is not very good.  It makes it difficult to read.  I would suggest looking at your IDE's menu options and use the format command.

It seems like you're trying to reinvent the wheel here. The &lt;ios&gt; header contains that option already.  To write the vector to a file as base 16 numbers, you can do that directly in the writeFile function:

void writeFile(std::string_view str, std::vector&lt;unsigned char&gt; const &amp; v)
{

    assert(str.data() != nullptr);
    std::ofstream f(str.data(), std::ios::binary);
    for(auto c : v)
    {
        if(f.is_open())
        {
            f &lt;&lt; std::hex &lt;&lt; (int)c;
        }
    }
    f.close();
}


If creating the string is more to the point than writing to the file, you can use a stringstream and do the same thing:

#include &lt;sstream&gt;

std::string hexify(std::vector&lt;unsigned char&gt; const &amp; v)
{
    std::stringstream ss;
    for(auto c : v)
    {
        ss &lt;&lt; std::hex &lt;&lt; (int)c;
    }
    return ss.str();
}


If characters with single digit character codes are to be used and the leading 0 is required, it's simply a matter of adding a couple of functions from the &lt;iomanip&gt; header:

&lt;&lt; std::setw(2) &lt;&lt; std::setfill('0') &lt;&lt; std::hex &lt;&lt; (int)c


If reinventing the wheel is the point, first there's a tag for that.

When you have a need for literal (magic) use a constant variable. It gives meaning to anonymous values.

Generally speaking when you're using iterators in a loop, since end() is past the last element, it's better to use not equals(!=) instead of less than.