title: Explanation of conversion of Ascii Char to Binary in C
body: <p>Can someone explain in a bit of detail how the following Char to Binary functions work in C?</p>
  
  <p>Specifically how the bit shifting and logical and work on an iteration</p>
  
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;limits.h&gt;
  void printCharAsBinary(char c) {
      int i;
      for(i = CHAR_BIT; i &gt;= 0; i--){
          printf("%d", ( unsigned int )( ( c &amp; (1 &lt;&lt; i) ) ? 1 : 0) );
      }
  }
  
  void printCharAsBinaryVer2(char c){
      int bit_index;
      for (bit_index = CHAR_BIT; bit_index &gt;= 0; --bit_index)
      {
          int bit = ( unsigned int ) (c &gt;&gt; bit_index) &amp; 1;
          printf("%d", bit);
      }
  }
  </code></pre>
  
  <p>You can see them in action here if that helps:
  <a href="http://code.geeksforgeeks.org/zC22WO" rel="nofollow noreferrer">http://code.geeksforgeeks.org/zC22WO</a></p>
  
  <hr>
  
  <p><strong>Update based on answers:</strong></p>
  
  <p><code>F</code> is <code>70</code> in decimal</p>
  
  <p><code>70</code> is <code>01000110</code> in binary</p>
  
  <p>With the following code:</p>
  
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;limits.h&gt;
  void printCharAsBinary(char c) {
      int i;
      for(i = CHAR_BIT; i &gt;= 0; i--){
          printf("%d", ( unsigned int )( ( c &amp; (1 &lt;&lt; i) ) ? 1 : 0) );
      }
  }
  </code></pre>
  
  <p>The iterations will be:</p>
  
  <pre><code>01000110 &amp; 10000000 = 00000000  RESULT is 0   so PRINT 0
  01000110 &amp; 01000000 = 01000000  RESULT is &gt; 0 so PRINT 1
  01000110 &amp; 00100000 = 00000000  RESULT is 0   so PRINT 0
  01000110 &amp; 00010000 = 00000000  RESULT is 0   so PRINT 0
  01000110 &amp; 00001000 = 00000000  RESULT is 0   so PRINT 0
  01000110 &amp; 00000100 = 00000100  RESULT is &gt; 0 so PRINT 1
  01000110 &amp; 00000010 = 00000000  RESULT is &gt; 0 so PRINT 1
  01000110 &amp; 00000001 = 00000000  RESULT is 0   so PRINT 0
  </code></pre>
  
  <p>With the following code:</p>
  
  <pre><code>void printCharAsBinaryVer2(char c){
      int bit_index;
      for (bit_index = CHAR_BIT; bit_index &gt;= 0; --bit_index)
      {
          int bit = ( unsigned int ) (c &gt;&gt; bit_index) &amp; 1;
          printf("%d", bit);
      }
  }
  
  00000000 &amp; 00000001 = 00000000  RESULT is 0   so PRINT 0
  00000001 &amp; 00000001 = 00000001  RESULT is &gt; 0 so PRINT 1
  00000010 &amp; 00000001 = 00000000  RESULT is 0   so PRINT 0
  00000100 &amp; 00000001 = 00000000  RESULT is 0   so PRINT 0
  00001000 &amp; 00000001 = 00000000  RESULT is 0   so PRINT 0
  00010001 &amp; 00000001 = 00000001  RESULT is &gt; 0 so PRINT 1
  00100011 &amp; 00000001 = 00000001  RESULT is &gt; 0 so PRINT 1
  01000110 &amp; 00000001 = 00000000  RESULT is 0   so PRINT 0
  </code></pre>