Dump memory buffer to hex text

来源:互联网 发布:2016年网络星期一 编辑:程序博客网 时间:2024/05/16 01:54
#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;}
原创粉丝点击