My case is as follows:
- I have a binary file I'm reading from with std::fstream read operation as (char*)
- My goal is to take every byte from the file, hex formatted, and then append it to a string variable
- The string variable should hold the entire content of the file formatted as per item 2.
For example, let's say I have the following binary file content:
D0 46 98 57 A0 24 99 56 A3
The way I'm formatting each byte is as follows:
stringstream fin;;
for (size_t i = 0; i < fileb_size; ++i)
{
fin << hex << setfill('0') << setw(2) << static_cast<uint16_t>(fileb[i]);
}
// this would yield the output "D0469857A0249956A3"
return fin.str();
Above approach works as expected, however, it is extremely slow for large files, which I understand; stringstream is meant for input formatting!
My question is, are there ways to optimize such code or the approach I'm taking all together? My only constrain is that the output should be in string format as shown above.
Thank you.