ZOJ1098-Simple Computer

模拟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';
		else
			buf[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;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值