【问题标题】:Convert binary file to hex notation将二进制文件转换为十六进制表示法
【发布时间】:2023-04-03 01:04:01
【问题描述】:

我想为我在参数中输入的二进制文件获取这个十六进制表示法:

我得到的输出和我想要的:

这是我写的代码,我没有好的十六进制数(对于 5A 之后的部分),我做错了什么?如何将我读取的字节正确转换为十六进制? 谢谢。

int main(int argc, char *argv[])
{

    std::string parameter = "The\\Path\\To\My\exe.exe";
    ifstream::pos_type size;
    char * memblock;

    ifstream file(parametre, 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;
        string str = string(memblock, size);
        string hexContent = "";
        int maxColumn = 0;

        std::stringstream ss;
        int column = 0;
        for (int i = 0; i < size; ++i) 
        {       
            ss << std::hex << (int)str[i];
            if (column == 8)
            {
                ss << '\n';
                column = 0;
            }
            column++;

        }

        std::string mystr = ss.str();
        cout << mystr;
    }
    return 0;
}

【问题讨论】:

  • 输入是什么,输出是什么?

标签: c++ arrays hex std


【解决方案1】:

看起来char 已在您的系统上签名,而您是签名扩展的受害者。比如 0x90 是负数,所以当它转换成 int 时,这个负数必须被传递,导致 0xffffff90。

解决方案

将文件读入unsigned char,或者从&lt;cstdint&gt;(如果可用)读取uint8_t,而不是char的数组。

char * memblock;

变成

uint8_t * memblock;

然后

memblock = new char[size];  

变成

memblock = new uint8_t[size];  

以后不要将其转换为string

string str = string(memblock, size);

毫无意义,您可以轻松地阅读memblock,并撤消我们之前建立的无符号性。刚读完memblock

别忘了

delete[] memblock;

当你完成时。这导致

更好的解决方案

使用std::vector。它会自行清理。

std::vector<uint8_t> memblock(size);
file.seekg(0, ios::beg);
file.read(reinterpret_cast<char*>(memblock.data()), size); 
//or file.read(reinterpret_cast<char*>(&memblock[0]), size); if no or data method 

【讨论】:

  • 谢谢你的帮助,我得到的是0x4d,0x5a,0x90,0x0,0x3,0x0,0x0,0x0,0x4...而不是0x4D,0x5A,0x90,0x00, 0x03,0x00,0x00,0x00, 0x04...你知道为什么我的数字的前0被截断了吗?谢谢。
  • 除了std::hex之外,你还需要使用一些额外的IO操纵器。有关详细信息,请参阅How can I pad an int with leading zeros when using cout << operator?
猜你喜欢
  • 2012-06-26
  • 2013-11-07
  • 1970-01-01
  • 2016-08-28
  • 2013-07-25
相关资源
最近更新 更多