读取二进制文件并将其转换为十六进制

读取二进制文件并将其转换为十六进制

本文介绍了C ++读取二进制文件并将其转换为十六进制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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;

   }

转换为十六进制:

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

当我用十六进制编辑器打开原始文件时,它显示如下:

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

有没有办法使用C ++来获得相同的期望输出?

Is there a way to get the same desired output using C++?

工作解决方案(by Rob):

Working solution (by 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 。请尝试以下方法之一:

There's your problem, right there. The constructor std::string::string(const char*) interprets its input as a nul-terminated string. So, only the characters leading up to '\0' are even passed to 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);

这篇关于C ++读取二进制文件并将其转换为十六进制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-23 16:29