title: How to quickly find the mismatch pattern in C
body: <p>Pre-condition:</p>
  
  <ol>
  <li>I can't use malloc.</li>
  <li>The error will happen within two bytes, means I can search word by word.</li>
  <li>My CPU is 32bit ARM11, no OS during this time.</li>
  <li>The first two bytes are important, if first two bytes are 0x00, that means all the rest of the bytes should be 0x00.</li>
  <li>If first two bytes are 0xFF, all the rest of the bytes should be 0xFF.</li>
  <li>If first two byte are not both 0x0000 and 0xFFFF, I just report an error, no need compare the rest.</li>
  </ol>
  
  <p>I read 256Kbyte block data, which should only have two states:</p>
  
  <ol>
  <li>all 0xFF</li>
  <li>all 0x00</li>
  </ol>
  
  <p>However, some data may change to a non-predictable value. I need find them out. I can search it one byte by one byte but seems too slow, so I decided to use dichotomy way to do it — which looks like:</p>
  
  <ol>
  <li>divide read out data into equal half, then compare.</li>
  <li>if both are not equal to all 0 or F, it means the data is corrupt at both side and I just need to find the earliest one, so I should give up the 2nd part and just divide the first part again. If only one side has problem, just give up the good one and focus on the problematic on.e</li>
  <li>loop above idea</li>
  <li>seems after 17 time, should find the point.</li>
  </ol>
  
  <p>How to write the code into loop? Do I need 17 different reference static data with different sizes and to use <code>memcmp</code>?</p>
  
  <p>My current code looks like:</p>
  
  <pre><code>unsigned char gReferData1[2] = {0xFF, 0xFF};
  unsigned char gReferData2[2] = {0x00, 0x00};
  
  int main(void)
  {
      int i = 0, result1 = 0, result2 =0;
  
      read_somewhere(readBuff, sizeof(readBuff)); //read out data
  
      //first test first two bytes
      result1 = memcmp(gReferData1, readBuff, 2); //test if 0xFFFF
      result2 = memcmp(gReferData2, readBuff, 2); //test if 0x0000
      if(result1 == 0)
      {
          // means all rest data should be 0xFF 
          for(i=2; i&lt;(0x40000/2); i++)
          {
              result1 = memcmp(gReferData1, readBuff + offet, 2); //test if 0xFFFF
              if(result1 != 0)
              {
                  //means find
                  // do error handle
              }
              offset+=2;
          }
      }
      else if(result2 == 0)
      {
          // means all rest data should be 0x00
          for(i=2; i&lt;(0x40000/2); i++)
          {
              result2 = memcmp(gReferData2, readBuff + offet, 2); //test if 0x0000
              if(result2 != 0)
              {
                  //means find
                  // do error handle
              }
              offset+=2;
          }
      }
      else
      {
          //just error
          // do error handle
      }
  
      return 0;
  }
  </code></pre>