<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DZone Snippets: print a binary number code</title>
    <link>http://snippets.dzone.com/posts</link>
    <pubDate>Fri, 25 Jul 2008 07:55:59 GMT</pubDate>
    <description>DZone Snippets: print a binary number code</description>
    <item>
      <title>Print a binary number in C</title>
      <link>http://snippets.dzone.com/posts/show/4716</link>
      <description>These are two functions that print the binary representation of an integer. The first simply prints it out, while the second only prints out the relevant digits (i.e. cuts the first x 0 digits) in groups of four.&lt;br /&gt;&lt;br /&gt;Explanation &lt;a href="http://compprog.wordpress.com/2007/10/29/bit-operations/"&gt;here&lt;/a&gt;.&lt;br /&gt;&lt;br /&gt;&lt;code&gt;&lt;br /&gt;#include &lt;stdio.h&gt;&lt;br /&gt;&lt;br /&gt;/* Print n as a binary number */&lt;br /&gt;void printbitssimple(int n) {&lt;br /&gt;	unsigned int i;&lt;br /&gt;	i = 1&lt;&lt;(sizeof(n) * 8 - 1);&lt;br /&gt;&lt;br /&gt;	while (i &gt; 0) {&lt;br /&gt;		if (n &amp; i)&lt;br /&gt;			printf("1");&lt;br /&gt;		else&lt;br /&gt;			printf("0");&lt;br /&gt;		i &gt;&gt;= 1;&lt;br /&gt;	}&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;/* Print n as a binary number */&lt;br /&gt;void printbits(int n) {&lt;br /&gt;	unsigned int i, step;&lt;br /&gt;&lt;br /&gt;	if (0 == n) { /* For simplicity's sake, I treat 0 as a special case*/&lt;br /&gt;		printf("0000");&lt;br /&gt;		return;&lt;br /&gt;	}&lt;br /&gt;&lt;br /&gt;	i = 1&lt;&lt;(sizeof(n) * 8 - 1);&lt;br /&gt;&lt;br /&gt;	step = -1; /* Only print the relevant digits */&lt;br /&gt;	step &gt;&gt;= 4; /* In groups of 4 */&lt;br /&gt;	while (step &gt;= n) {&lt;br /&gt;		i &gt;&gt;= 4;&lt;br /&gt;		step &gt;&gt;= 4;&lt;br /&gt;	}&lt;br /&gt;&lt;br /&gt;	/* At this point, i is the smallest power of two larger or equal to n */&lt;br /&gt;	while (i &gt; 0) {&lt;br /&gt;		if (n &amp; i)&lt;br /&gt;			printf("1");&lt;br /&gt;		else&lt;br /&gt;			printf("0");&lt;br /&gt;		i &gt;&gt;= 1;&lt;br /&gt;	}&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;int main(int argc, char *argv[]) {&lt;br /&gt;	int i;&lt;br /&gt;	for (i = 0; i &lt; 16; ++i) {&lt;br /&gt;		printf("%d = ", i);&lt;br /&gt;		printbitssimple(i);&lt;br /&gt;		printf("\n");&lt;br /&gt;	}&lt;br /&gt;&lt;br /&gt;	return 0;&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;&lt;/code&gt;</description>
      <pubDate>Tue, 30 Oct 2007 11:53:18 GMT</pubDate>
      <guid>http://snippets.dzone.com/posts/show/4716</guid>
      <author>scvalex (Alexandru Scvortov)</author>
    </item>
  </channel>
</rss>
