C++读取二进制文件并转换为十六进制
C++ read binary file and convert to hex
我在读取二进制文件并将其字节转换为十六进制表示时遇到一些问题。
到目前为止我尝试过的:
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;
}
转换为十六进制:
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();
}
结果:53514C69746520666F726D61742033
。
当我用十六进制编辑器打开原始文件时,它显示的是:
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
有没有一种方法可以使用C++获得相同的期望输出?
工作解决方案(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)
这就是你的问题。构造函数std::string::string(const char*)
将其输入解释为以nul结尾的字符串。因此,甚至只有通向' '
的字符被传递到ToHex
。试试其中一个:
std::string tohexed = ToHex(std::string(memblock, memblock+size), true);
std::string tohexed = ToHex(std::string(memblock, size), true);
相关文章:
- 将字符指针十六进制转换为字符串并保存在文本文件C++中
- 将十六进制转换为 DEC
- 将字符指针中的十六进制转换为十进制
- 使用 std::hex 将十六进制转换为十进制
- 将40个字节长的数据框从十六进制转换为二进制,然后转换为十进制
- 如何将十六进制转换为十进制
- 在C++中将十六进制转换为uint8_t
- 从十六进制转换为LPCVoid,切断了一半地址
- 将十六进制转换为可打印的字符串/字符
- 将 QString 十六进制转换为 ASCII 值
- 我如何在 C++ 中将变量从十六进制转换为 dec
- 混淆在C++中将十六进制转换为二进制
- C++中的十进制到十六进制转换代码
- 如何在C++中将十六进制转换为IEEE 754 32位浮点
- 十进制到十六进制转换错误
- 十进制到十六进制转换c++内置函数
- 如何将十六进制转换为字符串?C++
- 将 3d 数组元素从十六进制转换为二进制以获得 bmp
- C++:将十六进制转换为十进制
- 将十六进制转换为签名的十二月