我的情况如下:
例如,假设我具有以下二进制文件内容:
D0 46 98 57 A0 24 99 56 A3
我格式化每个字节的方式如下:
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();
上面的方法可以正常工作,但是,对于大文件来说,它的运行速度非常慢,据我了解; stringstream用于输入格式!
我的问题是,有什么方法可以优化此类代码,或者我可以一起使用?我唯一的约束是输出应为字符串格式,如上所示。
谢谢你。
最佳答案
std::stringstream
相当慢。它不会进行预分配,并且总是涉及复制字符串,至少要检索一次。同样,可以手动编码为十六进制的转换速度更快。
我认为这样的效果可能会更好:
// Quick and dirty
char to_hex(unsigned char nibble)
{
assert(nibble < 16);
if(nibble < 10)
return char('0' + nibble);
return char('A' + nibble - 10);
}
std::string to_hex(std::string const& filename)
{
// open file at end
std::ifstream ifs(filename, std::ios::binary|std::ios::ate);
// calculate file size and move to beginning
auto end = ifs.tellg();
ifs.seekg(0, std::ios::beg);
auto beg = ifs.tellg();
// preallocate the string
std::string out;
out.reserve((end - beg) * 2);
char buf[2048]; // larger = faster (within limits)
while(ifs.read(buf, sizeof(buf)) || ifs.gcount())
{
for(std::streamsize i = 0; i < ifs.gcount(); ++i)
{
out += to_hex(static_cast<unsigned char>(buf[i]) >> 4); // top nibble
out += to_hex(static_cast<unsigned char>(buf[i]) & 0b1111); // bottom nibble
}
}
return out;
}
它附加到预分配的字符串上,以最大程度地减少复制并避免重新分配。