lex:converting hex to dec
Andrew Henderson
I am trying to build a simple lexical analysis with flex and bison, but I have a problem with converting hex to dec in my lexer.l. Here are my codes.
hex (0)([x]|[X])([0-9][A-Fa-f])+
5{hex}{count++;printf("%d\t(hex,%s)\n",count,yytext);}
1 Answer
ohhh!I solved the problem! I just need to add two functions like c program and change the type of my output.
{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;}