Re: Parsing binary data in flex

Tim Van Holder <[email protected]>
Newsgroups gmane.comp.lex.flex.general
Message-ID <[email protected]>
Mohammed H Mehkri wrote:
> Is there any way to recognise bits in flex. Suppose I want to recognise
> 15bits of a particular sequence, is it possible to do so?
> 
> I couldnt find anything about it in flex manual nor I could fine
> anything useful on net.

Yes and no.  It's not possible to do this with standard flex.
But, you can override flex's I/O routines such as YYINPUT to
read bytes from the input stream and send a text representation
to flex.
Something like:

char
my_yyinput()
{
static char current_byte[9];
static int current_bit = -1;
  if (current_bit < 0) {
  int byte = fget(yyin);
    if (byte == EOF)
      memset(current_byte, 0, sizeof current_byte);
    else {
      for (int i = 0; i < 8; ++i)
        current_byte[7 - i] = ((byte & (1 << i)) ? '1' : '0');
    }
    current_bit = 0;
  }
  {
  char result = current_byte[current_bit++];
    if (current_bit > 7)
      current_bit = -1;
    return result;
  }
}

Then you can simply recognize bit patterns in flex:

"100111011001101" {
  do_something();
}

Note: this is untested, but I think it _should_ work (although
you may have to also add some mechanism to reset the statics in
my_yyinput()).
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.