Dump memory buffer to hex text

本文介绍了一个简单的C语言程序,该程序可以将内存缓冲区的内容以十六进制形式打印出来,并同时显示对应的ASCII字符。这对于调试和查看内存内容非常有用。程序使用了标准的C库函数,并通过循环逐行输出数据。
#include <stdio.h>
#include <string.h>
#include <ctype.h>

void dmpbuf(FILE *stream, const unsigned char* buffer, unsigned int length)
{
    const int N = 16;           // define maximum number of bytes of each line
    int i, nRead, addr = 0;
    char s[N * 3 + 1];          // string buffer
    char tmpbuf[32];            // temp buffer

    fprintf(stream, "/n");
    fprintf(stream, " ADDRESS | 00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F |      ASSCII     /n");
    fprintf(stream, "-----------------------------------------------------------------------------/n");

    while (length > 0) {
        // calculate number of bytes to output this line
        nRead = (length > N) ? N : length;
        length -= nRead;

        // output address
        fprintf(stream, "%08X | ", addr);

        // output hex contents
        s[0] = '/0';
        for (i = 0; i < nRead; i++) {
            sprintf(tmpbuf, "%02X ", buffer[addr+i]);
            strcat(s, tmpbuf);
        }
        fprintf(stream, "%s", s);

        // output alignment
        for (i = 0; i < N - nRead; i++) {
            fprintf(stream, "%3s", " ");
        }
        fprintf(stream, "| ");

        // output ascii characters
        for (i = 0; i < nRead; i++) {
            s[i] = isprint(buffer[addr+i]) ? buffer[addr+i] : '.';
        }
        s[i] = '/0';
        fprintf(stream, "%s", s);
        fprintf(stream, "/n");

        addr += nRead;
    }
}

int main()
{
    unsigned char buffer[253];

    for (int i = 0; i < sizeof(buffer); i++) {
        buffer[i] = i;
    }

    dmpbuf(stdout, buffer, sizeof(buffer));
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值