Convert binary file to hex notation

旧街凉风 提交于 2020-12-08 05:08:40

问题


I would like to obtain this hex notation for a binary I enter in parameter:

The output I obtain and what I want:

This is the code I written, I don't have the good hex number (for the part after 5A) , what I am doing wrong ? How to convert properly the byte I read to hex ? Thanks.

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;
}

回答1:


Looks like char is signed on your system and you are the victim of sign extension. For example 0x90 is a negative, so when it's converted into an int, that negativity has to be carried through, resulting in 0xffffff90.

Solution

Read the file into unsigned char, or uint8_t from <cstdint> if it is available, instead of an array of char.

char * memblock;

becomes

uint8_t * memblock;

then

memblock = new char[size];  

becomes

memblock = new uint8_t[size];  

and don't convert it into a string later.

string str = string(memblock, size);

is pointless, you could just as easily have read from memblock, and undoes the unsigned-ness we've established earlier. Just read out of memblock

Do not forget to

delete[] memblock;

when you are done. That leads to

Better solution

Use a std::vector. It cleans up after itself.

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 


来源:https://stackoverflow.com/questions/52506820/convert-binary-file-to-hex-notation

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!