gpt4 book ai didi

C++读取二进制文件并转换为十六进制

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:47:46 24 4
gpt4 key购买 nike

我在读取二进制文件并将其字节转换为十六进制表示时遇到了一些问题。

到目前为止我尝试了什么:

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 结尾的字符串。因此,只有 '\0' 之前的字符甚至会传递给 ToHex。请尝试以下方法之一:

std::string tohexed = ToHex(std::string(memblock, memblock+size), true);
std::string tohexed = ToHex(std::string(memblock, size), true);

关于C++读取二进制文件并转换为十六进制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9621893/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com