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

Dev*_*oot 4 c++ hex binary-data

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

到目前为止我尝试过的:

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;

   }
Run Code Online (Sandbox Code Playgroud)

转换为十六进制:

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();
}
Run Code Online (Sandbox Code Playgroud)

结果: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
Run Code Online (Sandbox Code Playgroud)

有没有办法使用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();
}
Run Code Online (Sandbox Code Playgroud)

Rob*_*obᵩ 5

char *memblock;
… 
std::string tohexed = ToHex(memblock, true);
…

string ToHex(const string& s, bool upper_case)
Run Code Online (Sandbox Code Playgroud)

那就是你的问题.构造函数std::string::string(const char*)将其输入解释为以空字符结尾的字符串.因此,只有导致的字符'\0'甚至被传递给ToHex.尝试其中之一:

std::string tohexed = ToHex(std::string(memblock, memblock+size), true);
std::string tohexed = ToHex(std::string(memblock, size), true);
Run Code Online (Sandbox Code Playgroud)