DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

owen has posted 5 posts at DZone. View Full User Profile

C Convert Buffer To Binary String

05.18.2006
| 31161 views |
  • submit to reddit
        // Sometimes one wants to see data in binary
// This method converts an arbitrary buffer to 1's and 0's

#include <stdio.h>
#include <stdlib.h>
#include <memory.h>
#include <string.h>

char *getBufferAsBinaryString(void *in)
{
	int pos=0;
	char result;
	char bitstring[256];
	memset(bitstring, 0, 256);
	unsigned int *input= (unsigned int *)in;
	for(int i=31;i>=0;i--)
	{
		if (((*input >> i) & 1)) result = '1';
		else result = '0';
		bitstring[pos] = result;
		if ((i>0) && ((i)%4)==0)
		{
			pos++;
			bitstring[pos] = ' ';
		}
		pos++;
	}
	return bitstring;
}
int main(int argc, char* argv[])
{
	int i=53003;
	char buffer[1024];
	char *s=getBufferAsBinaryString(&i);
	strcpy(buffer, s);
	printf("%s\n", buffer);
}

produces this output:
0000 0000 0000 0000 1100 1111 0000 1011    

Comments

Snippets Manager replied on Fri, 2007/01/26 - 8:26pm

I would not recommend using this code snippet. This function does not convert a buffer. It converts a 32-bit integer to a binary string. The bitstring array does not need to be 256 bytes long. The for loop increments 32 times, plus the 7 spaces every four bits and the null character at the end of the string gives me 40 bytes. You don't need the call to memset. You can actually just add bitstring[pos] = '\0' before the return statement. Why have the input parameter be a void pointer? The function will not work correctly if you pass in anything not 32 bits. You are assuming that an int is 32 bits. If you #include you can actually determine the size of an int rather than assuming it is 32 bits. CHAR_BIT * sizeof(int) will give you the size of an int in bits. If you pass in the address of an int then cast it to the address of an unsigned int, that is bad form. In main() you create the array buffer of 1024 bytes. Why? The result will always be 40 bytes. You could have atleast had buffer[] and bitstring[] the same size. Finally, and this is a big one, you return the address of the array bitstring. The moment the function returns to main() the auto-variables, including bitstring, are released. They might still exist in memory but that will only be by luck. Using the strcpy in main hides this fact but even that is not guaranteed to work. It depends on how strcpy was implemented.