[英]C++ read binary file and convert to hex
I'm having some problems reading a binary file and converting it's bytes to hex representation. 我在读取二进制文件并将其字节转换为十六进制表示时遇到一些问题。
What I've tried so far: 到目前为止我尝试过的:
ifstream::pos_type size;
char * memblock;
ifstream file (toread, ios::in|ios::binary|ios::ate);
if (file.is_open())
{
size = file.tellg();
memblock = new char [size];
file.seekg (0, ios::beg);
file.read (memblock, size);
file.close();
cout << "the complete file content is in memory" << endl;
std::string tohexed = ToHex(memblock, true);
std::cout << tohexed << std::endl;
}
Converting to hex: 转换为十六进制:
string ToHex(const string& s, bool upper_case)
{
ostringstream ret;
for (string::size_type i = 0; i < s.length(); ++i)
ret << std::hex << std::setfill('0') << std::setw(2) << (upper_case ? std::uppercase : std::nouppercase) << (int)s[i];
return ret.str();
}
Result: 53514C69746520666F726D61742033
. 结果:
53514C69746520666F726D61742033
。
When I open the original file with a hex editor, this is what it shows: 当我用十六进制编辑器打开原始文件时,它显示的是:
53 51 4C 69 74 65 20 66 6F 72 6D 61 74 20 33 00
04 00 01 01 00 40 20 20 00 00 05 A3 00 00 00 47
00 00 00 2E 00 00 00 3B 00 00 00 04 00 00 00 01
00 00 00 00 00 00 00 00 00 00 00 01 00 00 00 00
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 00 00 00 00 00 00 05 A3
00 2D E2 1E 0D 03 FC 00 06 01 80 00 03 6C 03 D3
Is there a way to get the same desired output using C++? 有没有办法使用C ++获得相同的所需输出?
Working solution (by Rob): 工作解决方案 (Rob):
...
std::string tohexed = ToHex(std::string(memblock, size), true);
...
string ToHex(const string& s, bool upper_case)
{
ostringstream ret;
for (string::size_type i = 0; i < s.length(); ++i)
{
int z = s[i]&0xff;
ret << std::hex << std::setfill('0') << std::setw(2) << (upper_case ? std::uppercase : std::nouppercase) << z;
}
return ret.str();
}
char *memblock;
…
std::string tohexed = ToHex(memblock, true);
…
string ToHex(const string& s, bool upper_case)
There's your problem, right there. 那就是你的问题。 The constructor
std::string::string(const char*)
interprets its input as a nul-terminated string. 构造函数
std::string::string(const char*)
将其输入解释为以空字符结尾的字符串。 So, only the characters leading up to '\\0'
are even passed to ToHex
. 因此,只有导致
'\\0'
的字符才会传递给ToHex
。 Try one of these instead: 尝试其中之一:
std::string tohexed = ToHex(std::string(memblock, memblock+size), true);
std::string tohexed = ToHex(std::string(memblock, size), true);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.