我试图用flex和bison构建一个简单的词法分析,但在我的lex.l中将十六进制转换为dec有问题。这是我的密码。
十六进制(0)(x-9)+{十六进制}{count++;printf(“%d\t(十六进制,%s)\n",计数,yytext);}
发布于 2022-05-24 09:00:56
哦哦!我解决了问题!我只需要添加两个函数,比如c程序,并改变输出的类型。
{hex} {count++;printf("%d\t(hex,%d)\n",count,hextodec(yytext));}
{oct} {count++;printf("%d\t(oct,%d)\n",count,octtodec(atoi(yytext)));}
int octtodec(int oct){
int dec=0,pos=0;
while (oct){
int a=oct%10;
dec += a * pow(8,pos);
pos++;
oct /= 10;
}
return dec;}
int hextodec(char *hex){
int dec=0,pos=0;
int len;
len=strlen(hex);
for (int i =2;i<len;i++){
if(hex[i]>='a'&&hex[i]<='f'){
dec=dec+(hex[i]-'a'+10)*pow(16,len-i-1);
}
else if(hex[i]>='A'&&hex[i]<='F'){
dec=dec+(hex[i]-'A'+10)*pow(16,len-i-1);
}
else{
dec+=(hex[i]-'0')*pow(16,len-i-1);
}
}
return dec;}
https://stackoverflow.com/questions/72336219
复制