NoFear

导航

打印内存【CSDN】

Posted on 2012-05-14 21:32  Fear_Hao  阅读(192)  评论(0编辑  收藏  举报
View Code
#include <string.h>
#include <stdio.h>

void printHexString(const void* buf , size_t size);
int main()
{
        char* pstr = new char[64];
        printHexString(pstr , 64);
        const char* ps = "Hello World!";
        printHexString(ps , 20);
        char* pstr2 = new char[64];
        printHexString(pstr2 , 64);
        return 0;
}

void printHexString(const void* buf , size_t size)
{
        char* str = (char*)buf;
        char line[512] = {0};
        const size_t lineLength = 16; // 8或者
        char text[24] = {0};
        char* pc;
        int textLength = lineLength;

        for (size_t ix = 0 ; ix < size ; ix += lineLength)
        {
                sprintf(line, "%.8xh: ", ix);
                // 打印进制
                for (size_t jx = 0 ; jx != lineLength ; jx++)
                {
                        if (ix + jx >= size)
                        {
                                sprintf(line + (11 + jx * 3), "   "); // 处理最后一行空白
                                if (ix + jx == size)
                                        textLength = jx;  // 处理最后一行文本截断
                        } else
                                sprintf(line + (11 + jx * 3), "%.2X ", * (str + ix + jx));
                }
                // 打印字符串
                {
                        memcpy(text, str + ix, lineLength);
                        pc = text;
                        while (pc != text + lineLength)
                        {
                                if ((unsigned char)*pc < 0x20) // 空格之前为控制码
                                        *pc = '.';                 // 控制码转成'.'显示
                                pc++;
                        }
                        text[textLength] = '\0';
                        sprintf(line + (11 + lineLength * 3), "; %s\n", text);
                }
                printf("%s", line);
        }
}