我将如何创建C ++中的十六进制转储程序? [英] How would I create a hex dump utility in C++?

查看:150
本文介绍了我将如何创建C ++中的十六进制转储程序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基本上,我需要用C ++写一个十六进制转储程序。它会是这个样子。

Basically, I need to write a hex dump utility using C++. It'll look something like this

(使用Visual Studio的Word文档的十六进制转储的部分)

我想提示输入一个文件名的用户,然后显示的十六进制值,以及翻译的ASCII字符。我还是新的二进制文件的工作,因此,如果你能保持它的简单,那会是多少AP preciated。

I want to prompt the user for a file name, and then display the hexadecimal values as well as the translated ASCII characters. I'm still new at working with binary files, so if you could keep it simple, that would be much appreciated.

推荐答案

我通常不这样做的盛情问题....不过,这并不需要太多敲这样的事情了,也许你可以借鉴一下。这里是一个没有廉价的方案,只是从标准输入和输出读大致相同的格式显示你。尝试一下在这里: http://ideone.com/mt1MLS

I don't normally do this for your kind of question.... But it doesn't take much to knock something like this up, and maybe you can learn from it. Here's a no-frills program that just reads from standard input and outputs in roughly the same format as you showed. Try it out here: http://ideone.com/mt1MLS

code

#include <iostream>
#include <iomanip>

using namespace std;

int main()
{
    unsigned long address = 0;
    char c;

    cout << hex << setfill('0');
    while( cin.good() )
    {
        int nread;
        char buf[16];

        for( nread = 0; nread < 16 && cin.get(buf[nread]); nread++ );
        if( nread == 0 ) break;

        // Show the address
        cout << setw(8) << address;

        // Show the hex codes
        for( int i = 0; i < 16; i++ )
        {
            if( i % 8 == 0 ) cout << ' ';
            if( i < nread )
                cout << ' ' << setw(2) << (unsigned)buf[i];
            else 
                cout << "   ";
        }

        // Show printable characters
        cout << "  ";
        for( int i = 0; i < nread; i++)
        {
            if( buf[i] < 32 ) cout << '.';
            else cout << buf[i];
        }

        cout << "\n";
        address += 16;
    }
    return 0;
}

输入

Hello there, this is a test binary file.
What do you think?

.

输出

00000000  48 65 6c 6c 6f 20 74 68  65 72 65 2c 20 74 68 69  Hello there, thi
00000010  73 20 69 73 20 61 20 74  65 73 74 20 62 69 6e 61  s is a test bina
00000020  72 79 20 66 69 6c 65 2e  0a 57 68 61 74 20 64 6f  ry file..What do
00000030  20 79 6f 75 20 74 68 69  6e 6b 3f 0a 0a 2e         you think?...

这篇关于我将如何创建C ++中的十六进制转储程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆