title: Parse and read data frame in C?
body: <p>I am writing a program that reads the data from the serial port on Linux. 
  The data are sent by another device with the following frame format:</p>
  
  <pre><code>|start | Command | Data               | CRC  | End |
  |0x02  | 0x41    | (0-127 octets)     |      | 0x03|
  ----------------------------------------------------
  </code></pre>
  
  <p>The Data field contains 127 octets as shown and octet 1,2 contains one type of data; octet 3,4 contains another data. I need to get these data</p>
  
  <p>I know how to write and read data to and from a serial port in Linux, but it is just to write and read a simple string (like "ABD")</p>
  
  <p>My issue is that I do not know how to parse the data frame formatted as above so that I can:</p>
  
  <ul>
  <li>get the data in octet 1,2 in the Data field</li>
  <li>get the data in octet 3,4 in the Data field</li>
  <li>get the value in CRC field to check the consistency of the data</li>
  </ul>
  
  <p>Here the sample snip code that read and write a simple string from and to a serial port in Linux:</p>
  
  <pre><code>int writeport(int fd, char *chars) {
      int len = strlen(chars);
      chars[len] = 0x0d; // stick a &lt;CR&gt; after the command
      chars[len+1] = 0x00; // terminate the string properly
      int n = write(fd, chars, strlen(chars));
      if (n &lt; 0) {
          fputs("write failed!\n", stderr);
          return 0;
      }
      return 1;                                                                                                           
  }
  
  int readport(int fd, char *result) {
      int iIn = read(fd, result, 254);
      result[iIn-1] = 0x00;
      if (iIn &lt; 0) {
          if (errno == EAGAIN) {
              printf("SERIAL EAGAIN ERROR\n");
              return 0;
          } else {
              printf("SERIAL read error %d %s\n", errno, strerror(errno));
              return 0;
          }
      }                    
      return 1;
  }
  </code></pre>
  
  <p>Does anyone please have some ideas?</p>