user1936709
user1936709

Reputation: 11

Parse file to hex

Assume that I have a file .img. I want to parse the file and display it by hex. This is my code reference in the internet. But the application display is null. Please help me to resolve it.

     int _tmain(int argc, _TCHAR* argv[])
      {
    const char *filename = "test.img";
    ifstream::pos_type size;
    char * memblock;
    ifstream file(filename, 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();

        std::string tohexed = ToHex(std::string(memblock, size), true);
        cout << tohexed << endl;
      }
      }


        string ToHex(const string& s, bool upper_case)  { 


    ostringstream ret;

    for (string::size_type i = 0; i < s.length(); ++i)
    {
        int z = (int)s[i];
        ret << std::hex << std::setfill('0') << std::setw(2) << (upper_case ? std::uppercase : std::nouppercase) << z;
    }

    return ret.str();
}

Upvotes: 0

Views: 431

Answers (1)

Potatoswatter
Potatoswatter

Reputation: 137800

That's way too much code.

It can help to define a class with operator<< to encapsulate custom formatting.

https://ideone.com/BXopcd

#include <iostream>
#include <iterator>
#include <algorithm>
#include <iomanip>

struct hexchar {
    char c;
    hexchar( char in ) : c( in ) {}
};
std::ostream &operator<<( std::ostream &s, hexchar const &c ) {
    return s << std::setw( 2 ) << std::hex << std::setfill('0') << (int) c.c;
}

int main() {
    std::copy( std::istreambuf_iterator<char>( std::cin ), std::istreambuf_iterator<char>(),
        std::ostream_iterator< hexchar >( std::cout ) );
}

Upvotes: 3

Related Questions