zju 1098 simple computers

模拟:

需要注意的是位数例如内存为8位,PC为8为,ACCU为8为的无符号整形。

#include<cstdio>
#include<cstdlib>
#include<memory.h>
#include<cstring>
enum INST{STA,LDA,BEQ,NOP,DEC,INC,JMP,HLT};
char str[30];
unsigned char accu;
unsigned char memory[32];
unsigned char  pc;
int main()
{
    int i,j,k,cur;
    bool flag;
           while(scanf("%s",str)!=EOF) 
    {
      memset(memory,0,sizeof(memory));

      for(i=0;i<8;i++)
             memory[0]=(memory[0]<<1)|(str[i]-'0');          
            for(j=1;j<=31;j++)
        {
            scanf("%s",str);
            for(i=0;i<8;i++)
                        memory[j]=(memory[j]<<1)|(str[i]-'0');

        }
        pc=0;
        accu=0;
        flag=true;
        while(flag)
        {
            switch(memory[pc]>>5)
            {
                case STA:
                    memory[memory[pc]&0x1f]=accu;
                    pc=++pc&0x1f;
                    break;
                              case LDA:
                     accu=memory[memory[pc]&0x1f];
                     pc=++pc&0x1f;
                     break;
                              case BEQ:
                     if(accu==0)
                     {
                    
                      pc=memory[pc]&0x1f;
                
                     }
                     else pc=++pc&0x1f;
                     break;
                  case NOP:
                     pc=++pc&0x1f;
                     break;
                  case DEC:
                     pc=++pc&0x1f;
                     accu--;
                     break;
                  case  INC:
                     pc=++pc&0x1f;
                     accu++;
                     break;
                  case JMP :
                     pc=memory[pc]&0x1f;
                     break;
                  case HLT:
                      for(i=7;i>=0;i--)
                      printf("%d",(accu>>i)&1); printf("\n");
                     flag=false;
                     break;


            }
        }
        
       
        
          }
    return 0;
  
}
原文地址:https://www.cnblogs.com/woaiyy/p/2525007.html