Never been to DZone Snippets before?

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

About this user

Owen Corpening

« Newer Snippets
Older Snippets »
Showing 1-2 of 2 total  RSS 

C convert buffer to binary string

// Sometimes one wants to see data in binary
// This method converts an arbitrary buffer to 1's and 0's

   1  
   2  #include <stdio.h>
   3  #include <stdlib.h>
   4  #include <memory.h>
   5  #include <string.h>
   6  
   7  char *getBufferAsBinaryString(void *in)
   8  {
   9  	int pos=0;
  10  	char result;
  11  	char bitstring[256];
  12  	memset(bitstring, 0, 256);
  13  	unsigned int *input= (unsigned int *)in;
  14  	for(int i=31;i>=0;i--)
  15  	{
  16  		if (((*input >> i) & 1)) result = '1';
  17  		else result = '0';
  18  		bitstring[pos] = result;
  19  		if ((i>0) && ((i)%4)==0)
  20  		{
  21  			pos++;
  22  			bitstring[pos] = ' ';
  23  		}
  24  		pos++;
  25  	}
  26  	return bitstring;
  27  }
  28  int main(int argc, char* argv[])
  29  {
  30  	int i=53003;
  31  	char buffer[1024];
  32  	char *s=getBufferAsBinaryString(&i);
  33  	strcpy(buffer, s);
  34  	printf("%s\n", buffer);
  35  }


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

c C++ convert hex to ascii

// Presented with hex such as 0x12345abc perhaps there is a spot in there
// which represents an ascii char - such as 53 would be 'S'
// Common when dealing with hardware-related data structures and wire
// protocols

   1  
   2  #include <stdio.h>
   3  #include <stdlib.h>
   4  
   5  /*
   6  *	To convert 53 to the character 'S':
   7  *	char returnVal = hexToString('5', '3');
   8  */
   9  char hexToAscii(char first, char second)
  10  {
  11  	char hex[5], *stop;
  12  	hex[0] = '0';
  13  	hex[1] = 'x';
  14  	hex[2] = first;
  15  	hex[3] = second;
  16  	hex[4] = 0;
  17  	return strtol(hex, &stop, 16);
  18  }
  19  int main(int argc, char* argv[])
  20  {
  21  	printf("%c\n", hexToAscii('5', '3'));
  22  }

produces this output:
S
« Newer Snippets
Older Snippets »
Showing 1-2 of 2 total  RSS