我正在尝试使用 flex 和 bison 构建一个简单的词法分析,但是在我的 lexer.l 中将十六进制转换为十进制时遇到问题。这是我的代码。
十六进制 (0)([x]|[X])([0-9][A-Fa-f])+
{hex}{count++;printf("%d\t(hex,%s)\n",count,yytext);}
ohhh!我解决了这个问题!我只需要添加两个函数,如 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;}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句