首页 > 其他 > 详细

showMem.c setMem.c

时间:2018-05-02 19:38:16      阅读:211      评论:0      收藏:0      [点我收藏+]
#ifndef MEMUTIL_H_INCLUDED
#define MEMUTIL_H_INCLUDED

// Show memory
void showMem(void *, unsigned);

// Setup memory
int setMem(void *, const char *);

#endif // MEMUTIL_H_INCLUDED

  

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

// Display memory
void showMem(void *p, unsigned size)
{
    char *buf = 0;
    int prs = 0;
    unsigned i;

	buf = (char *)malloc(size * 9);
    printf("Show %p, count %u bits.\n", p, size * 8);
    for (i = 0; i < size; i++)
    {
        char ch = ((char *)p)[i]; // Get char p[i]
        int j;

        for (j = 0; j < 8; j++) // p[i] to 8 bit unsigned int
        {
            unsigned tmp = 0;

            tmp = ch >> (8 - j - 1) & 1;
            sprintf(&buf[prs], "%u", tmp % 2);
            prs = strlen(buf);
        }
        sprintf(&buf[prs], " ");
        prs++;
    }
    buf[prs - 1] = ‘\0‘;
    puts(buf);
}

  

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#include "MemUtil.h"

// Setup memory
// Return:
// 0  -Setting succeed
// !0 -Setting failed
int setMem(void *p, const char *c)
{
    int le;
    char *str = 0; // 去除空格的副本
    int i;
    int j;
    char ch;

    le = strlen(c);
    i = le - 1;
    str = (char *)malloc(le * 8 / 9 + 2);
    str[0] = ‘\0‘;

    // 去除空格
    i = 0;
    while ((ch = *(char *)c++) != ‘\0‘)
    {
        if (ch == ‘ ‘)
            continue;
        if (ch == ‘1‘ || ch == ‘0‘)
        {
            str[i++] = ch;
            str[i] = ‘\0‘;
        } else {
            printf("错误, 未知的字符: %c.", ch);
            return !0;
        }
    }
    if ((le = strlen(str)) % 8 != 0)
    {
        printf("拒绝执行, 长度错误: %d.\n", le % 8);
        return !0;
    }

    i = 0;
    j = le / 8;
    for (; i < j; i++)
    {
        char tmp = 0;
        int k = 0;

        for (; k < 8; k++)
        {
            tmp |= (str[i * 8 + k] ^ 0x30) << (7 - k);
        }
        ((char *)p)[i] = tmp;
    }
    return 0;
}

  

showMem.c setMem.c

原文:https://www.cnblogs.com/develon/p/8982037.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!