C convert buffer to binary string
// 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