ZOJ1098-Simple Computer

来源:互联网 发布:仿手绘软件 编辑:程序博客网 时间:2024/05/09 18:37

模拟CPU

要注意的几个地方

pc > 31 accu < 0 accu > 255

#include <cstdio>enum Instructions{iSTA,iLDA,iBEQ,iNOP,iDEC,iINC,iJMP,iHLT};int strToInt( char * str ){int result = 0;for(int i=7;i>=0;i--){if( str[7 - i] == '1' )result += ( 1 << i );}return result;}void intToStr(int x){char buf[9 + 1];buf[8] = '\0';for(int i=0;i<8;i++){if( ( x >> ( 7 - i) ) & 1 )buf[i] = '1';elsebuf[i] = '0';}printf("%s\n", buf);}int memBuf[32 + 1];char strBuf[8 + 1];int main(){int pc;int accu;while( scanf("%s", strBuf) != EOF ){pc = 0;accu = 0;memBuf[0] = strToInt( strBuf );for(int i=1;i<32;i++){scanf("%s", strBuf);memBuf[i] = strToInt(strBuf);}while(true){int inst = memBuf[pc++];pc %= 32;int type = inst >> 5;int addr = inst % 32;if( type == iSTA ){memBuf[addr] = accu;}else if( type == iLDA ){accu = memBuf[addr];}else if( type == iBEQ ){if( accu == 0 )pc = addr;}else if( type == iNOP ){}else if( type == iDEC ){accu--;if(accu < 0)accu = 255;}else if( type == iINC ){accu++;if( accu > 255 )accu = 0;}else if( type == iJMP ){pc = addr;}else //if( type == iHLT ){break;}}intToStr(accu);}return 0;}


原创粉丝点击