title: UTF-8 encoding in C with getchar()
body: <p>I have to make a code that takes characters with UTF-8 encoding and "translate"them into Unicode.  You can check here what a UTF-8 is <a href="http://en.wikipedia.org/wiki/UTF-8" rel="nofollow">https://en.wikipedia.org/wiki/UTF-8</a>. I am a C beginner so I have three restrictions placed on me:</p>
  
  <ol>
  <li>I must use <code>getchar()</code> </li>
  <li>It is forbidden to use arrays</li>
  <li>I am only interested in Unicode characters with 1,2,3 and 4 bytes</li>
  </ol>
  
  <p>So I have this code which is totally functional for 4 bytes(I know I must use <code>!= EOF</code> for every <code>getchar();</code> but for now this is not my problem)</p>
  
  <pre><code>#include &lt;stdio.h&gt;
  
  int main(void) {
          int ch1, ch2, ch3, ch4, c;
          ch1 = getchar();
          ch2 = getchar();
          ch3 = getchar();
          ch4 = getchar();
          if ((ch1 &amp; 0xF8) != 0xF0 || (ch2 &amp; 0xC0) != 0x80 ||
                          (ch3 &amp; 0xC0) != 0x80 || (ch4 &amp; 0xC0) != 0x80) {
                  printf("Error in UTF-8 4-byte encoding\n");
                  return 1;
          }
          c = ((ch1 &amp; 0x07) &lt;&lt; 18) | ((ch2 &amp; 0x3F) &lt;&lt; 12) |
                          ((ch3 &amp; 0x3F) &lt;&lt; 6) | (ch4 &amp; 0x3F);
          printf("c = %05X\n", c);
          return 0;
  }
  </code></pre>
  
  <p>My question: I cannot understand how I can use <code>getchar()</code> for 1-2-3 bytes. I mean, I must read all the <code>getchar</code> functions in the beginning and then use <code>ch1</code> for 1-byte characters and <code>ch1</code>, <code>ch2</code> for 2 bytes characters OR I must do it like this. (By the way, the code below it is not functional, it gives me an infinite loop; I just use it as a example of my thought.)</p>
  
  <pre><code>#include &lt;stdio.h&gt;
  
  int main (void) {
          int ch1, ch2, ch3, ch4, c;
  
          if (c &gt;=0x0000 &amp;&amp; c&lt;=0x007F ){
               ch1=getchar();
              while (ch1 !=EOF){
                  if ((ch1 &amp; 0x80) != 0x00) {
                      printf("Error in UTF-8 1-byte encoding\n");
                      return 1;   
                     }
                   c = ((ch1 &amp; 0x80) &lt;&lt; 7);
                   printf("c = %05X\n", c);
                  }
          }
  </code></pre>