0

ファイル.imgがあると仮定します。ファイルを解析して16進数で表示したい。これはインターネットでの私のコードリファレンスです。ただし、アプリケーションの表示はnullです。それを解決するのを手伝ってください。

     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();
}
4

1 に答える 1

3

それはあまりにも多くのコードです。

operator<<カスタム書式設定をカプセル化するクラスを定義すると役立ちます。

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 ) );
}
于 2013-01-10T03:01:12.327 に答える