binary to decimal conversion - yacc program

 bindec.lex

***************************************

%{

/* Definition section */

#include<stdio.h>

#include<stdlib.h>

#include"bindec.tab.h"

extern int yylval;

%}

%option noyywrap

/* Rule Section */

%%

0 {yylval=0;return ZERO;}

1 {yylval=1;return ONE;}


[ \t] {;}

\n return 0;

. return yytext[0];

%%


bindec.y
********************************************
%{
/* Definition section */
#include<stdio.h>
#include<stdlib.h>
%}
%token ZERO ONE

/* Rule Section */
%%
N: L {printf("The decimal is=%d\n", $$);}
L: L B {$$=$1*2+$2;}
   | B {$$=$1;}
B: ZERO {$$=$1;}
   |ONE {$$=$1;};
%%

//driver code
int main()
{
while(yyparse());
}
int yyerror(char *s)
{
printf("\n Invalid Expression \n");
}

Execution
*************************
$ bison -d bindec.y
$ flex bindec.lex
$ gcc lex.yy.c bindec.y.c
$ ./a.out
101101
The decimal is=45



Comments

Popular posts from this blog

KTU Compiler Lab CSL411 - Dr Binu V P

lexical analyzer for a c program

13.Precedence and conflict resolution in yacc