I searched char* to hex string before but implementation I found adds some non-existent garbage at the end of hex string. I receive pa
I've found good example here Display-char-as-Hexadecimal-String-in-C++:
std::vector randomBytes(n);
file.read(&randomBytes[0], n);
// Displaying bytes: method 1
// --------------------------
for (auto& el : randomBytes)
std::cout << std::setfill('0') << std::setw(2) << std::hex << (0xff & (unsigned int)el);
std::cout << '\n';
// Displaying bytes: method 2
// --------------------------
for (auto& el : randomBytes)
printf("%02hhx", el);
std::cout << '\n';
return 0;
Method 1 as shown above is probably the more C++ way:
Cast to an unsigned int
Usestd::hexto represent the value as hexadecimal digits
Usestd::setwandstd::setfillfromto format
Note that you need to mask the cast int against0xffto display the least significant byte:
(0xff & (unsigned int)el).Otherwise, if the highest bit is set the cast will result in the three most significant bytes being set to
ff.