题目:给定了规则,先把十六进制代码翻译成二进制,然后在用对应规则翻译成语句,规则如下
要点:1 string读入以后,用+=的性质练成一个长的string,或者用老师建议的getchar也可以
2 用到了十六进制与二进制之间的转换,也可以用打表法
#include <string.h>
#include <cstdlib>
#include <cmath>
#include <ctgmath>
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
char operand[4];
char Instruction[16][5] = {"ADD","SUB","MUL","DIV","MOV","BREQ","BRLE","BRLS","BRGE","BRGR","BRNE","BR","AND","OR","XOR","NOT"};
void PrintInstruction(char m){
if (m >= '0' && m <= '9') {
cout<<Instruction[m - '0']<<" ";
}
else cout<<Instruction[m - 'A' + 10]<<" ";
}
void PrintOperand(char a,char b){
if(a == '0' && b == '0') cout<<"R";
if(a == '0' && b == '1') cout<<"$";
if(a == '1' && b == '0') cout<<"PC+";
}
void Operand(char OxCome[4]){
//十六进制到二进制的转换太烦人啦
//直接用了之前的一道题目的代码,所以m的大小是那个题目中的42
char m[42] = {0};
char * pEnd;
long long decimal = strtol(OxCome, &pEnd , 16);//16-》10
for(int i = 0;i < 42;i++) {
int temp = decimal % 2;
if(temp <= 9) m[42 - 1 - i] = temp + '0';
else m[42 - 1 - i] = temp - 10 + 'A';
decimal /= 2;
if(decimal == 0) break;
}
int i = 26;//26~41存储
for (int Except0=26; Except0 <42; Except0++) {
if(m[Except0]=='\0') m[Except0] = '0';
}
//for(; i < 42; i++)
//printf("%c",m[i]);
PrintOperand(m[i], m[i+1]);
char CutTheOxNum[14];
int temp = 0;
for(int t = i+2; t < 42; t++)
CutTheOxNum[temp++] = m[t];
decimal = strtol(CutTheOxNum, &pEnd , 2);
cout<<decimal;
}
void SetOne(string m,int &start){
PrintInstruction(m[start]);
int t = 0;
for (int i = start + 1; i <= start + 4; i++) {
operand[t++]=m[i];
}
Operand(operand);cout<<",";
t = 0;
for (int i = start + 5; i <= start + 8; i++) {
operand[t++]=m[i];
}
Operand(operand);
start = start + 9;
}
void SetTwo(string m,int &start){
PrintInstruction(m[start]);
int t = 0;
for (int i = start + 1; i <= start + 4; i++) {
operand[t++]=m[i];
}
Operand(operand);
start += 5;
}
void SetThree(string m,int &start){
PrintInstruction(m[start]);
int t = 0;
for (int i = start + 1; i <= start + 4; i++) {
operand[t++]=m[i];
}
Operand(operand);cout<<",";
t = 0;
for (int i = start + 5; i <= start + 8; i++) {
operand[t++]=m[i];
}
Operand(operand);cout<<",";
t = 0;
for (int i = start + 9; i <= start + 12; i++) {
operand[t++]=m[i];
}
Operand(operand);
start = start + 13;
}
int main()
{
string s,m;
while(cin>>m){
if (m.length()<30) {
s+=m;break;
}
s+=m;
}
//cout<<s;
int it = 0;
while(it != s.length()){
char temp = s[it];
if (temp >= '0' && temp <= '4') {
SetOne(s, it);
cout<<endl;
}
if ((temp >= '5' && temp <= '9') || (temp >= 'A' && temp <= 'B') || temp == 'F') {
SetTwo(s, it);
cout<<endl;
}
if (temp >= 'C' && temp <= 'E') {
SetThree(s, it);
cout<<endl;
}
}
return 0;
}
/*
BB67459090D43E6FA05BCE1C6F12CB
D8A43CABC
0D43E6FA05BCE1C6F12CBD8A43CABC
*/