showMem.c setMem.c 及其改进

MemUtil.h

#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

showMem.c

 #include <stdio.h>
 #include <stdlib.h>
 #include <string.h>
 
 
 char *showMem(void *p, unsigned size)
 {
     char *buf = 0;
     int prs = 0;
     unsigned i = 0;
     unsigned j = 0;
     char ch = '\0';
     unsigned tmp = 0;
 
     if ((buf = (char *)malloc(size * 9)) == 0)
     {
         fprintf(stderr, "Execute failed, PC have not memory.\n");
         return 0;
     }
 
     printf("Show %p, count %u bits.\n", p, size * 8);
     for (i = 0; i < size; i++)
     {
         ch = ((char *)p)[i]; // Get char p[i]
 
 
         for (j = 0; j < 8; j++) // p[i] to 8 bit unsigned int
         {
             tmp = ch >> (7 - j) & 1;
             buf[prs++] = (tmp == 0 ? 0x30 : 0x31);
         }
         buf[prs++] = ' ';
     }
     buf[prs - 1] = '\0';
     puts(buf);
     return buf;
 }

setMem.c

 #include <stdio.h>
 #include <string.h>
 #include <stdlib.h>
 
 #include "MemUtil.h"
 
 // Setting memory
 // Return:
 //      设置完成的字节数
 //      -1 代表错误
 int setMem(void *p, const char *c)
 {
     int le = 0;
     char *str = 0; // 去除空格的副本
     int i = 0;
     int j = 0;
     char ch = 0;
 
     le = strlen(c);
     str = (char *)malloc(le);
 
     // 去除空格和换行
     while ((ch = *(char *)c++) != '\0')
     {
         if (ch == ' ' || ch == '\n')
             continue;
         if (ch == 0x31 || ch == 0x30)
         {
             str[i++] = ch;
         } else {
             printf("Oops, dead character %c.", ch);
             return -1;
         }
     }
     str[i] = '\0';
 
     if ((le = strlen(str)) % 8 != 0)
     {
         printf("You setting data is fucking, 错误的余数 %d.\n", le % 8);
         return -1;
     }
 
     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 j;
 }
posted @ 2018-05-02 19:29  develon  阅读(235)  评论(0编辑  收藏  举报