<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DZone Snippets: convert code</title>
    <link>http://snippets.dzone.com/posts</link>
    <pubDate>Sun, 07 Sep 2008 05:18:16 GMT</pubDate>
    <description>DZone Snippets: convert code</description>
    <item>
      <title>C convert buffer to binary string</title>
      <link>http://snippets.dzone.com/posts/show/2076</link>
      <description>// Sometimes one wants to see data in binary&lt;br /&gt;// This method converts an arbitrary buffer to 1's and 0's&lt;br /&gt;&lt;br /&gt;&lt;code&gt;&lt;br /&gt;#include &lt;stdio.h&gt;&lt;br /&gt;#include &lt;stdlib.h&gt;&lt;br /&gt;#include &lt;memory.h&gt;&lt;br /&gt;#include &lt;string.h&gt;&lt;br /&gt;&lt;br /&gt;char *getBufferAsBinaryString(void *in)&lt;br /&gt;{&lt;br /&gt;	int pos=0;&lt;br /&gt;	char result;&lt;br /&gt;	char bitstring[256];&lt;br /&gt;	memset(bitstring, 0, 256);&lt;br /&gt;	unsigned int *input= (unsigned int *)in;&lt;br /&gt;	for(int i=31;i&gt;=0;i--)&lt;br /&gt;	{&lt;br /&gt;		if (((*input &gt;&gt; i) &amp; 1)) result = '1';&lt;br /&gt;		else result = '0';&lt;br /&gt;		bitstring[pos] = result;&lt;br /&gt;		if ((i&gt;0) &amp;&amp; ((i)%4)==0)&lt;br /&gt;		{&lt;br /&gt;			pos++;&lt;br /&gt;			bitstring[pos] = ' ';&lt;br /&gt;		}&lt;br /&gt;		pos++;&lt;br /&gt;	}&lt;br /&gt;	return bitstring;&lt;br /&gt;}&lt;br /&gt;int main(int argc, char* argv[])&lt;br /&gt;{&lt;br /&gt;	int i=53003;&lt;br /&gt;	char buffer[1024];&lt;br /&gt;	char *s=getBufferAsBinaryString(&amp;i);&lt;br /&gt;	strcpy(buffer, s);&lt;br /&gt;	printf("%s\n", buffer);&lt;br /&gt;}&lt;br /&gt;&lt;/code&gt;&lt;br /&gt;&lt;br /&gt;produces this output:&lt;br /&gt;0000 0000 0000 0000 1100 1111 0000 1011</description>
      <pubDate>Thu, 18 May 2006 20:54:04 GMT</pubDate>
      <guid>http://snippets.dzone.com/posts/show/2076</guid>
      <author>ocorpening (Owen Corpening)</author>
    </item>
  </channel>
</rss>
