lnlidawei

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

c:  machine0 - 机器语言的模型机

 

 

 

 

一、源码

 1 [wit@eagle src]$ cat  machine0.c
 2 #include<stdio.h>
 3 #include<stdlib.h>
 4 #include<string.h>
 5 
 6 
 7 
 8 
 9 // explains each one of directives
10 void execute(char* in)
11 {
12   printf("\n");
13   printf("directive = %s\n", in);
14   if( memcmp(in,"0000", 4) ==0 )
15   {
16     printf("directive: mov \n");
17   }
18   else if( memcmp(in,"0001",4)==0 )
19   {
20     printf("directive: add \n");
21   }
22   else if( memcmp(in,"0010",4)==0 )
23   {
24     printf("directive: sub \n");
25   }
26   else if( memcmp(in,"0011",4)==0 )
27   {
28     printf("directive: mul \n");
29   }
30   else if( memcmp(in,"0100",4)==0 )
31   {
32     printf("directive: div \n");
33   }
34   else
35   {
36     printf("\tERROR: '%s', the directive is not defined.\n", in);
37   }
38   printf("\n");
39 }
40 
41 
42 
43 
44 // deal with diretvies
45 void directive(char *in)
46 {
47 
48   // parameter 'in' limited 4 bits
49   int len = strlen(in);
50   if( len == 4 )
51   {
52     // printf("os: directive()  running... \n");
53     execute(in);
54   }
55   else
56   {
57     printf("\n");
58     printf("\tERROR: directives of inputing is wrong, reinput directives ...\n");
59     printf("\tDIRECTIVE: 4bits; eg:\"0000\",\"0101\". \n");
60     printf("\n");
61   }
62 
63 }
64 
65 
66 
67 
68 // main programming of directives
69 void run(char* in)
70 {
71   directive(in);
72 }
73 
74 
75 
76 
77 int main(int argc, char* argv[], char* envp[])
78 {
79   // printf("argc = %d\n", argc);
80   for(int i=1; i<argc; i++)
81   {
82     run(argv[i]);
83   }
84 
85 
86   return 0;
87 }

 

 

 

 

 

 

二、运行结果:

 1 [wit@eagle src]$ gcc -g -o machine0 machine0.c && ./machine0 0000 1000 0001 1100 0010 1110
 2 
 3 directive = 0000
 4 directive: mov
 5 
 6 
 7 directive = 1000
 8         ERROR: '1000', the directive is not defined.
 9 
10 
11 directive = 0001
12 directive: add
13 
14 
15 directive = 1100
16         ERROR: '1100', the directive is not defined.
17 
18 
19 directive = 0010
20 directive: sub
21 
22 
23 directive = 1110
24         ERROR: '1110', the directive is not defined.
25 
26 [wit@eagle src]$
27 [wit@eagle src]$

 

 

 

 

三、参考资料:无

 

posted on 2023-02-26 01:38  lnlidawei  阅读(17)  评论(0编辑  收藏  举报