Lex: Converting Hex to Dec

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])+

{hex}{count++;printf("%d\t(hex,%s)\n",count,yytext);}

5

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;}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

James H. Sterling

James H. Sterling

Environmental Science & Climate Journalist

James Sterling reports on renewable energy developments, climate policy, ecological conservation, and green tech innovations around the globe.

Share this article
Twitter Facebook Pinterest